'How to map postgres's "time without time zone" to JPA/Hibernate entity?
Current implementation:
@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));
The error I get all the time:
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.
Solution 1:[1]
You should use java.sql.Time instead. Are there a specific reason you are using LocalDateTime? Example with 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
}
}
Solution 2:[2]
You do not need a converter. You can use annotations (as per JPA 2.2). This works with Postgres.
@Column(nullable = false, columnDefinition = "TIMESTAMP WITH TIME ZONE")
private OffsetDateTime createdOn;
Instantiation can be done as per:
@PrePersist
private void prePersist() {
this.createdOn = OffsetDateTime.now(ZoneId.of("UTC"));
}
The example here uses OffsetDateTime but for LocalDateTime you can use
@Column(nullable = false, columnDefinition = "TIMESTAMP WITHOUT TIME ZONE")
private LocalDateTime createdOn;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Paizo |
| Solution 2 | Coen Damen |
