简体   繁体   中英

How to do it with JPA Criteria API?

我如何在JPA2中进行条件查询,这等效于使用和不使用元模型的JPQL?

SELECT p FROM Employee e JOIN e.phones p WHERE e=:empl
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Phone> criteriaQuery = cb.createQuery(Phone.class);
Root<Employee> employee = criteriaQuery.from(Employee.class);
CollectionJoin<Employee, Phone> phone = employee.join(Employee_.phones);
criteriaQuery.where(cb.equal(employee, empl);
criteriaQuery.select(phone);
TypedQuery<Phone> query = em.createQuery(criteriaQuery);
List<Phone> phones = query.getResultList();

That said, I see no point in replacing a simple, obvious JPQL query with the horrendous, unreadable lines of code above. Criteria queries are useful to dynamically construct queries, but JPQL shines for static queries like the one you have.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM