Adam Bien's Weblog
New Java 8 Date and JPA 2.1 Integration
JPA 2.1 does not directly support the java.time API. However, with an AttributeConverter implementation you can easily integrate Java 8 (or any other dates) with JPA:
import java.time.Instant;
import java.time.LocalDate;
import java.util.Date;
import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
@Converter(autoApply = true)
public class LocalDateConverter implements AttributeConverter<LocalDate, Date> {
@Override
public Date convertToDatabaseColumn(LocalDate date) {
Instant instant = Instant.from(date);
return Date.from(instant);
}
@Override
public LocalDate convertToEntityAttribute(Date value) {
Instant instant = value.toInstant();
return LocalDate.from(instant);
}
}
The @Converter(autoApply = true) will automatically activate the converter and keep your domain classes clean:
import java.time.LocalDate;
@Entity
public class Spaceship {
@Id
private long id;
private String name;
private int speed;
private LocalDate arrival;
}
The example above was taken from Java 8 with Java EE 7. See you at http://airhacks.com or Virtual Dedicated Workshops / consulting!
Posted at 08:09AM Dec 30, 2014 by Adam Bien Comments[0] | Views/Hits: 1622
NEW workshop: Java EE 7 and Java 8, January 27th, 2015, Airport Munich