0

I have a domain object with properties below, upon form submission only the completionDate binds from the form input, while dateRaised is null. No errors except for validation errors. I tried changing the dateRaised type to java.time.LocalDate and it works fine. Is binding to java.time.LocalDateTime already supported?

@NotNull
@Column(name = "date_raised", nullable = false)
@DateTimeFormat(iso = ISO.DATE_TIME)
private java.time.LocalDateTime dateRaised;

@Column(name = "completion_date")
@DateTimeFormat(iso = ISO.DATE)
private java.time.LocalDate completionDate;
aalmero
  • 345
  • 2
  • 18

1 Answers1

0

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.

How to persist LocalDate and LocalDateTime with JPA

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();
Community
  • 1
  • 1
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132