规范中的 spring-data 子查询

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12061502/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 05:19:31  来源:igfitidea点击:

spring-data subquery within a Specification

springsubquerycriteria-apispring-data

提问by John Kroubalkian

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.

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

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.

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

Thanks in advance.

提前致谢。

回答by Pieter

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);
        }
    }
);

is the equivalent of the following jpql query:

相当于以下 jpql 查询:

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