问题描述
能否在HQL / JPQL中将LocalDate
与LocalDateTime
进行比较?这是我对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}
解决方法
因此,您应该通过以下方式创建自定义方言:
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);