Persist Java 8 LocalTime in JPA

China☆狼群 提交于 2019-12-01 06:25:51

问题


I have a Java 8 LocalTime in one of my entity .

private final LocalTime departureTime;

It is a Spring Boot 1.3.6 application with Spring Data Rest . I use Jsr310JpaConverters to support Java 8 time module for JPA .

When I save the LocalTime variable to MySql , date at which the LocalTime variable is saved is also being persisted to the database . Suppose if I save 18:00:00 on 1st Jan 2016 , it is persisted as 2016-01-01 18:00:00 . I want to save only the time . ie 18:00:00 . Any solutions ?

Thanks in Advance


回答1:


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.




回答2:


"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.



来源:https://stackoverflow.com/questions/38864625/persist-java-8-localtime-in-jpa

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