spring-data subquery within a Specification

前端 未结 1 1701
独厮守ぢ
独厮守ぢ 2020-12-09 10:05

Spring-data, Oliver Gierke\'s excellent library, has something called a Specification (org.springframework.data.jpa.domain.Specification). With it you can generate several

相关标签:
1条回答
  • 2020-12-09 10:29
    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:

    SELECT e FROM Employee e WHERE e IN (
        SELECT emp FROM Project p JOIN p.employees emp WHERE p.name = :projectName
    )
    
    0 讨论(0)
提交回复
热议问题