Failed to save java.time.ZonedDateTime using hibernate PostgresSQL

I have an object that extends an audit entity class called AbstractAuditingEntity, in which one of the fields

@CreatedDate @Column(name = "created_date", nullable = false) @JsonIgnore private ZonedDateTime createdDate 

Above the field, it is mapped to a database field named "created_date" type "timestamp without time zone" .

But while saving this object, PostgresSQL throws an error as follows:

 Caused by: org.postgresql.util.PSQLException: ERROR: column "created_date" is of type timestamp without time zone but expression is of type bytea Hint: You will need to rewrite or cast the expression. 

I was looking for the same error and found a solution here: Postgresql UUID supported by Hibernate?

But the solution is for java.util.UUID , the solution proposes to add the @Type(type="pg-uuid") annotation @Type(type="pg-uuid") in the field with the UUID type.

Is there such a ready-to-use type value like pg-uuid for ZonedDateTime ? Any reference for different values โ€‹โ€‹of hibernate @Type annotation constants?

Or should I write my own deserializer class? How to write such a deserializer class link to link?

 PostgresSQL Version : 9.6, <liquibase-hibernate5.version>3.6</liquibase-hibernate5.version> 
+5
source share
1 answer

For Hibernate 5.2, it should just work out of the box.

In version 5.0, you can add a dependency to support:

 <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-java8</artifactId> <version>${hibernate.version}</version> </dependency> 

For 4.3, you can use the JPA 2.1 converter:

 @Converter public class TimestampConverter implements AttributeConverter<ZonedDateTime, Timestamp> { @Override public Timestamp convertToDatabaseColumn(ZonedDateTime zonedTime) { if (zonedTime == null) { return null; } return new Timestamp(zonedTime.toInstant().toEpochMilli()); } @Override public ZonedDateTime convertToEntityAttribute(Timestamp localTime) { if (localTime == null) { return null; } return ZonedDateTime.ofInstant(Instant.ofEpochMilli(localTime.getTime()), ZoneId.systemDefault()); } } 

Then annotate your attribute with @Convert :

 @Convert(converter = TimestampConverter.class) private ZonedDateTime createdDate; 

I note that your database column is TIMESTAMP . It really should be TIMESTAMP WITH TIME ZONE , especially if your clientโ€™s time zone changes.

+3
source

Source: https://habr.com/ru/post/1262971/


All Articles