首页 > 解决方案 > 使用 Jpa 规范调用表值函数

问题描述

我有 2 个查询,一个是使用包含进行预搜索,第二个是使用第一个查询的结果,使用 JPA 规范。

而且我只需要保留一个查询,因为它不能做 cb.function(CONTAINS,...) 我创建了一个表值函数,使它包含在 SQL Server 中。

现在的问题是我不能从 JPA 规范中调用这个表值函数:

    public static Specification<CreditApplication> tryCustomFunction(String first, String last) {
        return (Root<CreditApplication> root, CriteriaQuery<?> query, CriteriaBuilder cb) -> {
            List<Predicate> andPredicates = new ArrayList<>();

            andPredicates.add(cb.equal(root.get(CreditApplication_.firstAndLastName),
                    cb.function("Z001.getApplicationsByFirstAndLastName", String.class, cb.literal(first), cb.literal(last))));

            return cb.and(andPredicates.toArray(new Predicate[]{}));
        };

    }

它说:

原因:com.microsoft.sqlserver.jdbc.SQLServerException:找不到列“Z001”或用户定义的函数或聚合“Z001.getApplicationsByFirstAndLastName”,或者名称不明确。

标量函数可以很好地使用这种表示法,但是这种类型的函数会抛出这个错误。

我尝试将其定义为存储过程,但也不起作用。

我正在使用 hibernate-core 5.3.7 和 Spring data jpa 2.1.3。

有什么帮助吗?

谢谢

标签: hibernatejpa

解决方案


如果您真的使用表值函数,您必须了解它只能在 from 子句中使用。Hibernate 不支持表值函数。

据我了解,您甚至不需要表值函数。您提到您尝试使用该CONTAINS功能。你尝试了什么?什么没用?

我认为以下应该可以正常工作:

public static Specification<CreditApplication> tryCustomFunction(String first, String last) {
    return (Root<CreditApplication> root, CriteriaQuery<?> query, CriteriaBuilder cb) -> {
        List<Predicate> andPredicates = new ArrayList<>();

        andPredicates.add(cb.isTrue(cb.function("CONTAINS", Boolean.class, root.get(CreditApplication_.firstAndLastName), cb.literal(first + " OR " + last))));

        return cb.and(andPredicates.toArray(new Predicate[0]));
    };

}

推荐阅读