【问题标题】:Compare LocalDate with LocalDateTime in HQL/JPQL在 HQL/JPQL 中比较 LocalDate 和 LocalDateTime
【发布时间】:2020-12-20 15:47:26
【问题描述】:

是否可以在 HQL/JPQL 中将 LocalDateLocalDateTime 进行比较?这是我对 spring 数据中存储库方法的查询,它应该返回每个所需日期的订单数量。订单实体中的字段deliveryDateTime 的类型为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 方法不存在。那么,有没有其他办法呢?

【问题讨论】:

  • 由于 DATE 是未知的 HQL/JPQL 函数,因此您收到此错误。您可以尝试在您的休眠方言中定义适当的功能,然后使用它。你用什么数据库? deliveryDateTime 列有什么数据库类型?
  • @SternK 我正在使用 postgres,对于 LocalDateTime 我有时间戳类型

标签: hibernate spring-data-jpa spring-data hql jpql


【解决方案1】:

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

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

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

@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);

【讨论】:

    猜你喜欢
    • 2023-01-31
    • 2017-01-06
    • 2017-11-27
    • 1970-01-01
    • 2020-02-05
    • 2015-05-30
    • 2014-05-24
    • 1970-01-01
    • 2021-06-04
    相关资源
    最近更新 更多