Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Persist java.time.Instant (JDK8) with JPA2/Hibernate

Tags:

Neither JPA nor Hibernate currently support the new date/time classes brought by JSR-310 in JDK8 (JPA ticket, Hibernate ticket). Nonetheless, I'd like to code with the JDK8 date/time classes as they are finally well designed. In particular, I'm interested in java.time.Instant, not in full support for all java.time.* types, as all my entities will use this particular class (or so I think now, at least :-)

One option is to write a type converter, as defined by JPA 2.1. However, our app server is JBoss EAP 6.3 which is JPA 2.0 but not 2.1 compatible, so this is out of the question for now.

The next option is to use a Hibernate user type (a blog post about converting other JSR-310 classes here).

Are there better options? Thanks.

like image 212
wishihadabettername Avatar asked Oct 19 '14 04:10

wishihadabettername


People also ask

Does hibernate support instant?

Hibernate supports Instant just fine already and allows changing the database timezone via hibernate. jdbc.

How do you persist LocalDate and LocalDateTime with JPA?

Set; @Entity public class MyObject { @Id private String id; private LocalDate startdate; private LocalDate enddate; public MyObject() {} public MyObject(LocalDate enddate) { this. startdate = LocalDate. now(); this. enddate = enddate; } ... }

Does JPA support instant?

time. Instant is the best choice to store a date into DB: it is the most likely TIMESTAMP and you are not depending by timezone, it is just a moment on the time. JPA supports LocalDate , LocalTime , LocalDateTime etc. but not Instant.

What is the latest version of JPA?

Jakarta Persistence 3.0 The JPA was renamed as Jakarta Persistence in 2019 and version 3.0 was released in 2020.


2 Answers

Either use Hibernate 5.2.0+ or for earlier Hibernate 5 add the following dependency:

    <dependency>         <groupId>org.hibernate</groupId>         <artifactId>hibernate-java8</artifactId>         <version>${hibernate.version}</version>     </dependency> 
like image 142
Lovro Pandžić Avatar answered Sep 20 '22 14:09

Lovro Pandžić


In Hibernate 5.2 onwards has this issue solved more fully - you no longer need to include the hibernate-java8 dependency from Ipandzic's comment and you can use java.time.* classes such as LocalDateTime or Instant without any additional steps. You also do not need to mark columns using java.util.LocalDateTime etc as Temporal anymore, the way you had to with the older java.util.Date approach.

Since Hibernate 5.2, the hibernate-java8 content has been merged into hibernate-core see the change notes here

like image 23
PryceJS Avatar answered Sep 18 '22 14:09

PryceJS