首页 > 解决方案 > 在 HQL/JPQL 中比较 LocalDate 和 LocalDateTime

问题描述

是否可以LocalDateLocalDateTimeHQL/JPQL 进行比较?这是我在 spring 数据中对存储库方法的查询,它应该返回每个所需日期的订单数量。deliveryDateTimeOrder 实体中的字段类型为LocalDateTime。我想忽略时间部分,只比较日期部分。

@Query("SELECT new OrderCountPerDate(DATE(o.deliveryDateTime), COUNT(o.id)) FROM Order o WHERE DATE(o.deliveryDateTime) IN :dates GROUP BY DATE(o.deliveryDateTime) ")
List<LocalDate> findValidOrderDates(List<LocalDate> dates);

我当前的代码给了我这个错误:

    java.lang.IllegalArgumentException: org.hibernate.QueryException: No data type for node: org.hibernate.hql.internal.ast.tree.MethodNode 
     \-[METHOD_CALL] MethodNode: '('
        +-[METHOD_NAME] IdentNode: 'DATE' {originalText=DATE}

看起来 DATE 方法不存在。那么,还有其他方法可以做到吗?

标签: hibernatespring-data-jpaspring-datahqljpql

解决方案


因此,您应该通过以下方式创建自定义方言:

import org.hibernate.dialect.PostgreSQL10Dialect;
import org.hibernate.dialect.function.StandardSQLFunction;
import org.hibernate.type.LocalDateType;
import org.hibernate.type.StandardBasicTypes;

public class MyDialect extends PostgreSQL10Dialect
{

   public MyDialect()
   {
      registerFunction( "my_date", new StandardSQLFunction( "date", LocalDateType.INSTANCE ) );
   }
}

在您的application.properties

spring.jpa.properties.hibernate.dialect=com.me.MyDialect

然后您可以my_date在 HQL/JPQL 查询中使用该函数:

@Query("select new com.me.OrderCountPerDate(my_date(o.deliveryDateTime), count(o.id)) from Order o where my_date(o.deliveryDateTime) in :dates group by my_date(o.deliveryDateTime) ")
List<OrderCountPerDate> findValidOrderDates(List<LocalDate> dates);

推荐阅读