Is there any way to map properties like java.time.LocalDate
and / or java.time.Instant
through JPA and / or Hibernate?
Is there any way to map properties like java.time.LocalDate
and / or java.time.Instant
through JPA and / or Hibernate?
Use JPA 2.1 Converters. With them you can map the types you want.
It works as if it were a JPA Converter.
It would be something like:
@Converter
public class CoverConverter implements AttributeConverter<Cover, String> {
@Override
public String convertToDatabaseColumn(Cover attribute) {
switch (attribute) {
case DUST_JACKET:
return "D";
case HARDCOVER:
return "H";
case PAPERBACK:
return "P";
default:
throw new IllegalArgumentException("Unknown" + attribute);
}
}
@Override
public Cover convertToEntityAttribute(String dbData) {
switch (dbData) {
case "D":
return DUST_JACKET;
case "H":
return HARDCOVER;
case "P":
return PAPERBACK;
default:
throw new IllegalArgumentException("Unknown" + dbData);
}
}
}
Just be careful not to confuse with the native Hibernate Converter. The problem with using the native hibernate converter is that you will not be able to portlet your project to another implementation.
As far as I know (and I've researched) it's still not possible to map, the new date classes that have been added in Java 8. Take a look at HERE .
It's worth taking a look at the specific implementations of Hibernate or Eclipselink to get some news.
Other than that, I still do not see why using java.time.*
instead of old java.util.Date
, you can use JodaTime
to make life easier, or even do a conversion to the type you need, since finally you have long
corresponding to milisecs
You can use the converters with the java.sql. * package in the this link .
@Converter(autoApply = true)
public class LocalDatePersistenceConverter implements
AttributeConverter<java.time.LocalDate, java.sql.Date> {
@Override
public java.sql.Date convertToDatabaseColumn(LocalDate entityValue) {
return java.sql.Date.valueOf(entityValue);
}
@Override
public LocalDate convertToEntityAttribute(java.sql.Date databaseValue) {
return databaseValue.toLocalDate();
}
}