JPA中的Java 8 Date Time api

san*_*ris 14 spring hibernate jpa java-8 spring-data-jpa

在jpa中集成Java 8 Date Time api的最佳方法是什么?

我添加了转换器:

@Converter(autoApply = true)
public class LocalDatePersistenceConverter implements AttributeConverter<LocalDate, Date> {

    @Override
    public Date convertToDatabaseColumn(LocalDate localDate) {
        return Date.valueOf(localDate);
    }

    @Override
    public LocalDate convertToEntityAttribute(Date date) {
        return date.toLocalDate();
    }
}
Run Code Online (Sandbox Code Playgroud)

@Converter(autoApply = true)
public class LocalDateTimePersistenceConverter implements AttributeConverter<LocalDateTime, Timestamp> {
    @Override
    public Timestamp convertToDatabaseColumn(LocalDateTime entityValue) {
        return Timestamp.valueOf(entityValue);
    }

    @Override
    public LocalDateTime convertToEntityAttribute(Timestamp databaseValue) {
        return databaseValue.toLocalDateTime();
    }
}
Run Code Online (Sandbox Code Playgroud)

一切似乎都很好,但我应该如何使用JPQL进行查询?我正在使用Spring JPARepository,目标是选择日期与给定日期相同的所有实体,唯一的区别是它作为LocalDateTime保存在实体中.

所以:

public class Entity  {

    private LocalDateTime dateTime;

    ...
}
Run Code Online (Sandbox Code Playgroud)

和:

@Query("select case when (count(e) > 0) then true else false end from Entity e where e.dateTime = :date")
public boolean check(@Param("date") LocalDate date);
Run Code Online (Sandbox Code Playgroud)

执行它时只给我异常,这是正确的.

Caused by: java.lang.IllegalArgumentException: Parameter value [2014-01-01] did not match expected type [java.time.LocalDateTime (n/a)]
Run Code Online (Sandbox Code Playgroud)

我尝试了很多方法,但似乎没有任何方法可行,是否可能?

xen*_*ide 7

hibernate-java8我相信Hibernate有一个扩展库, 它本身支持许多时间类型.

你应该在编写转换器之前使用它.

在hibernate中5.2你不需要这个额外的库,它是核心的一部分.


小智 0

您是否在“class”元素中的 persistence.xml 中添加了 LocalDatePersistenceConverter 和 LocalDateTimePersistenceConverter ?