Persist Java 8 LocalTime in JPA

五迷三道 提交于 2019-12-01 09:08:19
Davijr

This exemple runs with: java 8, JPA 2.1, Hibernate 4.3.5.

You can implement a JPA AttributeConverter, if you are using JPA 2.1 and Hibernate earlier release of 5.0 version:

import java.sql.Time;
import java.time.LocalTime;

import javax.persistence.AttributeConverter;
import javax.persistence.Converter;

/**
 * Converter to persist LocalDate and LocalDateTime with 
 * JPA 2.1 and Hibernate older than 5.0 version
 **/

@Converter(autoApply = true)
public class LocalTimeAttributeConverter implements AttributeConverter<LocalTime, Time>{

    @Override
    public Time convertToDatabaseColumn(LocalTime localTime) {
        return (localTime == null ? null : Time.valueOf(localTime));
    }

    @Override
    public LocalTime convertToEntityAttribute(Time time) {
        return (time == null ? null : time.toLocalTime()); 
    }

}

Or if you are using Hibernate 5.0 (or later) you can add the dependency of maven:

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-java8</artifactId>
    <version>5.1.0.Final</version>
</dependency>

Notes -> The mapping of the entities is the same.

"Jsr310JpaConverters" offers only a small subset of the possible range of AttributeConverters that a typical project would need for handling java.time types. Sadly its LocalTimeConverter (presumably what is used here), converts to (java.util.)Date, so you get the time+date stored.

One solution would be to write your own JPA 2.1 AttributeConverter for java.time.LocalTime that converts it to java.sql.Time.

Other JPA providers (e.g DataNucleus) provide such things out of the box.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!