首页 > 解决方案 > 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(数据类型)。

标签: hibernatespring-data-jpahibernate-criteriacriteria-apicriteriaquery

解决方案


如果你想渲染这个 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"))


推荐阅读