hibernate - 在 HQL/JPQL 中比较 LocalDate 和 LocalDateTime
问题描述
是否可以LocalDate
与LocalDateTime
HQL/JPQL 进行比较?这是我在 spring 数据中对存储库方法的查询,它应该返回每个所需日期的订单数量。deliveryDateTime
Order 实体中的字段类型为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 方法不存在。那么,还有其他方法可以做到吗?
解决方案
因此,您应该通过以下方式创建自定义方言:
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);
推荐阅读
- reactjs - 在 React 上管理用户从游戏“房间”的退出?
- php - 为什么在我从 PHP 5.6 迁移到 7.3 之后,函数“session_regenerate_id”停止工作?
- javascript - 通过字符串从对象数组和子对象数组中获取动态值
- php - 如果您在另一个文件夹中有 index.php,如何在主页中设置它?
- c# - 无法从 GET 响应中获取数据
- reactjs - ./node_modules/material-ui-icons/AccessAlarm.js 找不到模块:无法解析“material-ui/SvgIcon”
- azure - Azure 应用服务 - 如何禁用弱密码?
- python - 从执行进程任务 SSIS 运行 .pyw 文件
- php - 尝试将 sql 结果作为 json 数据类型回显时出现语法错误
- python - python:如何直接从字节字符串变量显示图像?