JPA 创建子查询// create CriteriaQuery instance, with...

// create CriteriaQuery instance, with root Employee
CriteriaQuery<Employee> q = cb.createQuery(Employee.class);
Root<Employee> emp = q.from(Employee.class);
// create Subquery instance, with root Employee
Subquery<Employee> sq = q.subquery(Employee.class);
Root<Employee> spouseEmp = sq.from(Employee.class);
// the subquery references the root of the containing query
sq.where(cb.equal(spouseEmp, emp.get(Employee_.spouse)))
.select(spouseEmp);
// an exists condition is applied to the subquery result:
q.where(cb.exists(sq));
q.select(emp).distinct(true);

等同于

SELECT DISTINCT emp
FROM Employee emp
WHERE EXISTS (
SELECT spouseEmp
FROM Employee spouseEmp
WHERE spouseEmp = emp.spouse)

欢迎加入JPA讨论群讨论学习!

234134357

你可能感兴趣的:(JPA子查询)