规范中的弹簧数据子查询

规范中的弹簧数据子查询

本文介绍了规范中的弹簧数据子查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Spring-data,Oliver Gierke 的优秀库,有一个叫做 规范(org.springframework.data.jpa.domain.Specification).有了它,您可以生成多个谓词来缩小搜索条件.

Spring-data, Oliver Gierke's excellent library, has something called a Specification (org.springframework.data.jpa.domain.Specification). With it you can generate several predicates to narrow your criteria for searching.

有人可以提供在规范中使用子查询的示例吗?

Can someone provide an example of using a Subquery from within a Specification?

我有一个对象图,搜索条件可能会变得很复杂.我想使用规范来帮助缩小搜索范围,但我需要使用子查询来查看对象图中的某些子元素(集合内)是否满足我的搜索需求.

I have an object graph and the search criteria can get pretty hairy. I would like to use a Specification to help with the narrowing of the search, but I need to use a Subquery to see if some of the sub-elements (within a collection) in the object graph meet the needs of my search.

提前致谢.

推荐答案

String projectName = "project1";
List<Employee> result = employeeRepository.findAll(
    new Specification<Employee>() {
        @Override
        public Predicate toPredicate(Root<Employee> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
            Subquery<Employee> sq = query.subquery(Employee.class);
            Root<Project> project = sq.from(Project.class);
            Join<Project, Employee> sqEmp = project.join("employees");
            sq.select(sqEmp).where(cb.equal(project.get("name"),
                    cb.parameter(String.class, projectName)));
            return cb.in(root).value(sq);
        }
    }
);

相当于下面的 jpql 查询:

is the equivalent of the following jpql query:

SELECT e FROM Employee e WHERE e IN (
    SELECT emp FROM Project p JOIN p.employees emp WHERE p.name = :projectName
)

这篇关于规范中的弹簧数据子查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 00:07