Compare LocalDate with LocalDateTime in HQL/JPQL

…衆ロ難τιáo~ 提交于 2021-02-11 14:53:24

问题


Is it possible to compare LocalDate with LocalDateTime in HQL/JPQL? This is my query of repository method in spring data which should return amount of orders per required dates. The field deliveryDateTime in Order entity has type LocalDateTime. I want to ignore time part and compare only date part.

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

My current code gives me this error:

    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}

It looks like DATE method doesn't exist. So, is there other way how to do it?


回答1:


So, you should create a custom dialect in the following way:

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

Set this dialect in your application.properties:

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

And then you can use the my_date function in your HQL/JPQL queries:

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


来源:https://stackoverflow.com/questions/63689184/compare-localdate-with-localdatetime-in-hql-jpql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!