java 如何在Spring Data R2DBC中将PostgreSQL的“无穷大”值Map到LocalDateTime?

bq3bfh9z  于 2023-02-18  发布在  Java
关注(0)|答案(1)|浏览(88)

如何在Spring Data R2DBC中将PostgreSQL的"无穷大"值Map到LocalDateTime?
Java字段,

private LocalDateTime expireOn;

在数据库中,当没有值或从API传递空值时,它会自动生成。

tvmytwxo

tvmytwxo1#

您需要创建一个转换器。示例转换器从我的项目:

import ru.pochta.abon.library.util.DateUtils;

import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
import java.time.ZonedDateTime;
import java.util.Calendar;
import java.util.TimeZone;

@Converter(autoApply = true)
public class ZonedDateTimeConverter implements     AttributeConverter<ZonedDateTime, Calendar> {
    @Override
    public Calendar convertToDatabaseColumn(ZonedDateTime entityAttribute) {
        if (entityAttribute == null) {
            return null;
        }
        return DateUtils.convertZDTtoCalendar(entityAttribute);
    }

    @Override
    public ZonedDateTime convertToEntityAttribute(Calendar databaseColumn) {
        if (databaseColumn == null) {
        return null;
        }

        return ZonedDateTime.ofInstant(databaseColumn.toInstant(),
            databaseColumn
                    .getTimeZone()
                    .toZoneId());
    }
}
...
(method from the class DateUtils)
public static Calendar convertZDTtoCalendar(ZonedDateTime zdt) {
    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(zdt.toInstant().toEpochMilli());
    calendar.setTimeZone(TimeZone.getTimeZone(zdt.getZone()));
    return calendar;
}

用法:

@Column(name = "create_date")
@Convert(converter = ZonedDateTimeConverter.class)
private ZonedDateTime createDate;

值'infinity'需要特殊处理。如果它是字符串,转换器将相应地实现AttributeConverter〈ZonedDateTime,String〉。Converter处理两个方向的转换。

相关问题