views:

409

answers:

2

Can I use Criteria queries with EJB3 entities? If so, how can I combine them with EntityManager?

A: 

JPA doesn't provide a Criteria API like in Hibernate. But you can use ejb3criteria, a library that provides an API based on Hibernate Criteria API design for EJB3 Persistence. ejb3criteria can be used with any EJB3 Persistence implementation.

Pascal Thivent
Thanks, it's exactly what I need! Have you ever tried it?
Tried, yes; used in production, no. This just means I didn't use it heavily, but I'm not saying "don't use it in production".
Pascal Thivent
+3  A: 

One of the new features introduced in the JPA 2.0 is the Criteria API. You need one of the JPA2 implementations:

Criteria queries are accessed through the EntityManager.getCriteriaBuilder(), and executed through the normal Query API.

EntityManager em = ...;
CriteriaBuilder qb = em.getCriteriaBuilder();
CriteriaQuery<Employee> query = qb.createQuery(Employee.class);
Root<Employee> employee = query.from(Employee.class);
query.where(qb.equal(employee.get("firstName"), "Bob"));
List<Employee> result = em.createQuery(query).getResultList();
Jacek S
True. But that's not part of JPA 1.0/EJB 3.0 which is what the question was about.
Pascal Thivent