hibernate - Convert(DATE, expr) 使用 CriteriaBuilder for Sql server 实现
问题描述
我正在使用 spring-data-jpa 并使用Specification
类实现动态查询。Sql Server 版本为 2019 for db
有一个查询,我需要将 datetime(timestamp) 截断为仅日期部分(没有时间),然后应用 where 条件。查询类似于:
select a from Table1 a where convert(DATE,date_col)>?
问题出在第一个参数上,即DATE(this is actually a datatype and not a literal)
.
我的代码在 toPredicate 方法中运行,该方法描述为:
public Predicate toPredicate(Root<T> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder)
我尝试过使用criteriabuilder.function
方法,但不明白如何在函数中包含 DATE(数据类型)。
解决方案
如果你想渲染这个 SQL,你必须SQLFunction
向 Hibernate 注册一个自定义来完成这个。
public class TruncateDate implements SQLFunction {
@Override
public boolean hasArguments() {
return true;
}
@Override
public boolean hasParenthesesIfNoArguments() {
return true;
}
@Override
public Type getReturnType(Type firstArgumentType, Mapping mapping) throws QueryException {
return firstArgumentType;
}
@Override
public String render(Type firstArgumentType, List args, SessionFactoryImplementor factory) throws QueryException {
return "convert(DATE," + args.get(0) + ")";
}
}
您必须在方言中注册该功能。
因此,如果方言按照指示进行扩展,则可以通过以下方式完成:
this.registerFunction("trunc_date", new TruncateDate());
然后你可以像这样使用它:criteriaBuilder.function('trunc_date', root.get("dateAttribute"))
推荐阅读
- javascript - 如何从 XMLHttpRequest 获取数据到 GridView QML
- node.js - Bull 单独的进程超时,“作业停止超过允许的限制”
- incremental-build - 为什么 Shake 认为此文件已更改?
- exception - pjweekday 常量,用于多天的工作日异常
- php - MySQL - 将 csv 文件导入现有数据库
- google-cloud-platform - Vision API WEB_DETECTION 中输出的站点过滤
- google-apps-script - 如何自动从 Google 表格的上一行复制公式?
- google-chrome - 在每次搜索/每个页面自动加载时从谷歌图像和搜索引擎中删除安全搜索按钮
- java - 无法将实例变量值发送到 sendkeys() 方法
- python - textblob .detect_language() 函数不起作用