Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to map java.time.Year and others java.time types using Hibernate

There's hibernate-java8 JAR providing adapters for a couple of classes like Instant, LocalDate, etc., but some classes from java.time, e.g., Year, Month, YearMonth are missing. These classes get stored like an unknown Serializable, which is needlessly wasteful.

Surely I could use an int year instead of Year year, but I don't think, it's a good idea.

It looks like writing the YearJavaDescriptor should be pretty easy, however, I wonder why it's missing. Especially in case of YearMonth, I'd strongly prefer an existing adapter, ist there any? Or am I doing something stupid?

I'm unsure as googling returns nothing.

like image 934
maaartinus Avatar asked Mar 28 '17 01:03

maaartinus


2 Answers

Try to create a converter - AttributeConverter implementation for this purpose.

I used in the past something like following:

@Entity
public class RealEstateAgency {
    @Column(name = "createdAt")
    @Convert(converter = ZonedDateTimeConverter.class)
    private ZonedDateTime creationDate;
}

@Converter(autoApply = true)
public class ZonedDateTimeConverter implements AttributeConverter<ZonedDateTime, Date> {
 
    public Date convertToDatabaseColumn(ZonedDateTime toConvert) {
        return toConvert == null ? null : Date.from(toConvert.toInstant());
    }
 
    public ZonedDateTime convertToEntityAttribute(Date toConvert) {
        return toConvert == null ? null : ZonedDateTime.from(toConvert
                .toInstant());
    }
}
like image 147
catch23 Avatar answered Sep 27 '22 02:09

catch23


If your JPA provider does not persist a type in a sensible manner (in this case because it is a Java8 class, which was added after JPA 2.1 was approved) then you need to define a JPA 2.1 AttributeConverter to convert it to a standard JPA persistable type (in this case something like java.sql.Date).

like image 23
Anuj Teotia Avatar answered Sep 23 '22 02:09

Anuj Teotia