Sunday, November 22, 2015

Using Java 8 Time API with JPA

We were using the Joda-Time API for replacement of Java Date API. After improvements on the Java 8 Time API we decided to move on to the Java 8 Time API. But JPA 2.1 does not have built in support for Java 8 time API because Java 8 released after. But we can still use Java 8 API using the attribute converters.

Here the example code for converting LocalDate to java.sql.Date for persisting to db.



With autoApply = true property this converter will be apply to all LocalDates so entities can be clean. If you don't want this feature then you can add @Convert(converter = LocalDateConverter.class) annotation to the fields.