0

How can I do Criteria Query in JPA2, which is equivalent to this JPQL with and without using metamodel?

SELECT p FROM Employee e JOIN e.phones p WHERE e=:empl
srnjak
  • 915
  • 7
  • 21

1 Answers1

1
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.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • Thanks for your answer. It works. I agree, that it is no point replacing that simple JPQL. I have dynamical query, but just this part I didn't know how to do. – srnjak Jul 14 '13 at 14:58
  • Ah. OK, then. Glad to have helped. – JB Nizet Jul 14 '13 at 15:00