Hibernate 4 with java.time.LocalDate and DATE() construct

If you use JPA 2.1 this is simple to do. Converters allow your JPA entities to use the new java.time.LocalDate and java.time.LocalDateTime classes. Simply define the needed converter classes:

LocalDatePersistenceConverter.java

import java.time.LocalDate;
import javax.persistence.AttributeConverter;
import javax.persistence.Converter;

@Converter
public class LocalDatePersistenceConverter implements AttributeConverter<LocalDate, java.sql.Date> {

  @Override
  public java.sql.Date convertToDatabaseColumn(LocalDate entityValue) {
    if (entityValue != null) {
      return java.sql.Date.valueOf(entityValue);
    }
    return null;
  }

  @Override
  public LocalDate convertToEntityAttribute(java.sql.Date databaseValue) {
    if (databaseValue != null) {
      return databaseValue.toLocalDate();
    }
    return null;
  }
}

LocalDateTimePersistenceConverter.java

import java.time.LocalDateTime;
import javax.persistence.AttributeConverter;
import javax.persistence.Converter;

@Converter
public class LocalDateTimePersistenceConverter implements AttributeConverter<LocalDateTime, java.sql.Timestamp> {

  @Override
  public java.sql.Timestamp convertToDatabaseColumn(LocalDateTime entityValue) {
    if (entityValue != null) {
      return java.sql.Timestamp.valueOf(entityValue);
    }
    return null;
  }

  @Override
  public LocalDateTime convertToEntityAttribute(java.sql.Timestamp databaseValue) {
    if (databaseValue != null) {
      return databaseValue.toLocalDateTime();
    }
    return null;
  }
}

And then annotate the appropriate entity property with the @Converter annotation:

@Convert(converter = LocalDatePersistenceConverter.class)
private LocalDate completedDate;

Update September 2015
Hibernate 5 natively supports the java 8 Date/Time APIs. Just ensure that the hibernate-java8 jar is on your class path.

Leave a Comment