JPA - Persist @Temporal LocalDate using a converter

Viewed 6612

Unable to compile code using @Temporal for LocalDate.

Entity code

...
@Temporal(TemporalType.DATE)
private LocalDate creationDate;

public LocalDate getCreationDate() {
    return this.creationDate;
}

public void setCreationDate(LocalDate creationDate) {
    this.creationDate = creationDate;
}
...

Converter code

@Converter(autoApply=true)
public class DateConverter implements AttributeConverter<LocalDate, Date> {

    @Override
    public Date convertToDatabaseColumn(LocalDate localDate) {
        return (localDate == null) ? null : Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
    }

    @Override
    public LocalDate convertToEntityAttribute(Date date) {
        return (date==null) ? null : Instant.ofEpochMilli(date.getTime()).atZone(ZoneId.systemDefault()).toLocalDate();
    }

}

persistence.xml

...
<persistence-unit name="HR">
    <class>test.Employee</class>
    <class>test.DateConverter</class>
</persistence-unit>
...

Environment

  1. JDK 8
  2. Eclipse JEE - 2018-09
  3. hibernate-jpa-2.1-api-1.0.2.Final.jar
  4. hibernate-validator-6.0.14.Final.jar
  5. hibernate-validator-cdi-6.0.14.Final.jar
  6. javax.el-3.0.1-b11.jar
  7. jboss-logging-3.3.2.Final.jar
  8. validation-api-2.0.1.Final.jar
  9. hibernate-java8-5.1.0.Final.jar
  10. hibernate-entitymanager-5.3.7.Final.jar
  11. classmate-1.3.4.jar

Eclipse compile error(at @Temporal annotation line, in entity code):

The persistent field or property for a Temporal type must be of type java.util.Date, java.util.Calendar or java.util.GregorianCalendar

Removing @Temporal compiles fine. Isn't it required for date and time classes(java.time) in Java8?

Please help resolve the problem, thanks.

1 Answers

The @Temporal annotation is not needed for the new java.time package of classes. It was needed for java.util.Date, because that "Date" was a an attempt at a one-class-fits-all solution, that only made things worse.

You don't need a converter, either.

Related