如何在jpa查询中将localdatetime转换为localdate?

kh212irz  于 2021-07-06  发布在  Java
关注(0)|答案(2)|浏览(672)

我有一个带场的物体 LocalDateTime dateTime . 我有以下存储库方法

@Query("select m from MyClass m " +
                "where m.dateTime >= :startDate and m.dateTime <= :endDate")
findAllByTradeTimeBetween(@Param("startDate") LocalDate startDate, 
                          @Param("endDate") LocalDate endDate);

如何获得 LocalDateLocalDateTime dateTime 用这种方法。现在我有个例外

Parameter value [2020-01-31] did not match expected type [java.time.LocalDateTime]

我该怎么修?

e7arh2l6

e7arh2l61#

将查询保存在localdatetime中,并为localdate版本添加api似乎更为严格。

@Query("select m from MyClass m " +
                "where m.dateTime >= :startDate and m.dateTime < :endDate")
findAllByTradeTimeBetween(@Param("startDate") LocalDateTime startDate, 
                          @Param("endDate") LocalDateTime endDate);

findAllByTradeTimeBetween(LocalDate startDate, LocalDate endDate) {
    return findAllByTradeTimeBetween(startDate.atStartOfDay(),
                                     endDate.plusDays(1).atStartOfDay());
}

这将打开一些可疑用法的api(使用localdatetimes)。

pbossiut

pbossiut2#

您可以使用javax.persistence.attributeconverter来自动化日期格式之间的转换。下面是converter类,它将自动将localdatetime对象转换为localdate和viceversa:

@SuppressWarnings("UnusedDeclaration")
    @Converter(autoApply = true)
    public class LocalDateConverter implements AttributeConverter<LocalDateTime, LocalDate> {
        @Override
        public LocalDate convertToDatabaseColumn(LocalDateTime localDateTime) {
            //convert localDateTime to LocalDate
        }

        @Override
        public LocalDateTime convertToEntityAttribute(LocalDate localDate) {
            // convert localDate to LocalDateTime
        }
    }

相关问题