在JPA中持久化Java 8 LocalTime [英] Persist Java 8 LocalTime in JPA
问题描述
我的一个实体中有一个Java 8 LocalTime.
I have a Java 8 LocalTime in one of my entity .
private final LocalTime departureTime;
这是带有Spring Data Rest的Spring Boot 1.3.6应用程序.我使用Jsr310JpaConverters支持JPA的Java 8时间模块.
It is a Spring Boot 1.3.6 application with Spring Data Rest . I use Jsr310JpaConverters to support Java 8 time module for JPA .
当我将LocalTime变量保存到MySql时,LocalTime变量的保存日期也一直保存到数据库中.假设我在2016年1月1日保存18:00:00,则将其保存为2016-01-01 18:00:00.我只想节省时间.即18:00:00.有解决方案吗?
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 ?
预先感谢
推荐答案
此示例运行于:Java 8,JPA 2.1,Hibernate 4.3.5.
This exemple runs with: java 8, JPA 2.1, Hibernate 4.3.5.
如果您使用的是JPA 2.1和Hibernate 5.0早期版本,则可以实现JPA AttributeConverter:
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());
}
}
或者,如果您使用的是Hibernate 5.0(或更高版本),则可以添加maven的依赖项:
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.
这篇关于在JPA中持久化Java 8 LocalTime的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!