【问题标题】:How to map postgres's "time without time zone" to JPA/Hibernate entity?如何将 postgres 的“没有时区的时间”映射到 JPA/Hibernate 实体?
【发布时间】:2018-09-08 12:26:51
【问题描述】:

当前实现:

@Getter(AccessLevel.NONE)
    @Setter(AccessLevel.NONE)
    @Column(name = "send_time", columnDefinition = "timestamp without time zone not null")
    private LocalTime sendTime;

    @Convert(converter=LocalTimeConverter.class)
    public LocalTime getSendTime() {
        return sendTime;
    }


    @Convert(converter=LocalTimeConverter.class)
    public void setLocalTime(LocalTime time) {
        this.sendTime = time;
    }

@Converter(autoApply = true)
public class LocalTimeConverter implements AttributeConverter<LocalDateTime, Timestamp>{

    @Override
    public Timestamp convertToDatabaseColumn(LocalDateTime zonedDateTime) {
        if(zonedDateTime == null) {
            return null;
        }
        return Timestamp.valueOf(zonedDateTime);
    }

    @Override
    public LocalDateTime convertToEntityAttribute(Timestamp sqlTime) {
        if(sqlTime == null) {
            return null;
        }
        return sqlTime.toLocalDateTime();
    }

}

object.setSendTime(LocalTime.of(11, 00, 00));

我一直得到的错误:

ERROR: column "send_time" is of type time without time zone but expression is of type bytea
  Hint: You will need to rewrite or cast the expression.

【问题讨论】:

  • 是您的访问类型字段还是属性?

标签: java postgresql hibernate spring-boot jpa


【解决方案1】:

您应该改用java.sql.Time。您使用LocalDateTime 是否有特定原因?以LocalTime 为例:

@Converter
public class MyConverter implements AttributeConverter<LocalTime, Time> {

    @Override
    public Time convertToDatabaseColumn(LocalTime localTime) {
        if(localTime == null){
            return null;
        }

        // convert LocalTime to java.sql.Time
    }

    @Override
    public LocalTime convertToEntityAttribute(Time time) {
        if(time == null){
            return null;
        }

        // convert java.sql.Time to LocalTime
    }
}

【讨论】:

    猜你喜欢
    • 2012-04-06
    • 2012-11-01
    • 2013-07-18
    • 1970-01-01
    • 1970-01-01
    • 2023-02-01
    • 2013-10-31
    • 2013-12-10
    • 1970-01-01
    相关资源
    最近更新 更多