You will need to implement the AttributeConverter<EntityType, DatabaseType>
to convert your dates.
The following blog, Thoughts on Java by Thorben Janssen, explains how to store a LocalDate
attribute in a DATE
column or a LocalDateTime
in a TIMESTAMP
column.
JPA 2.1 was released before Java 8 and therefore doesn't support the new Date and Time API. If you want to use the new classes (in the right way), you need to define the conversion to java.sql.Date
and java.sql.Timestamp
yourself. This can be easily done by implementing the AttributeConverter<EntityType, DatabaseType>
interface and annotating the class with @Converter(autoApply=true)
. By setting autoApply=true
, the converter will be applied to all attributes of the EntityType
and no changes on the entity are required.
@Converter(autoApply = true)
public class LocalDateAttributeConverter implements AttributeConverter<LocalDate, Date> {
@Override
public Date convertToDatabaseColumn(LocalDate locDate) {
return (locDate == null ? null : Date.valueOf(locDate));
}
@Override
public LocalDate convertToEntityAttribute(Date sqlDate) {
return (sqlDate == null ? null : sqlDate.toLocalDate());
}
}
The conversion of the attribute is transparent to the developer and the LocalDate
attribute can be used as any other entity attribute. You can use it as a query parameter for example.
LocalDate date = LocalDate.of(2015, 8, 11);
TypedQuery<MyEntity> query = this.em.createQuery("SELECT e FROM MyEntity e WHERE date BETWEEN :start AND :end", MyEntity.class);
query.setParameter("start", date.minusDays(2));
query.setParameter("end", date.plusDays(7));
MyEntity e = query.getSingleResult();