How to define dynamic queries using the Criteria API
JPA 2.0 defines a query criteria API to simplify dynamic query creation. With JPQL dynamic queries would require performing string concatenations to build queries dynamically from web forms or dynamic content. JPQL is also not checked until runtime, making typos more common. The criteria API using a set of Java interfaces to allow queries to be dynamically constructed, and reduces runtime typos with compile time checking.
Criteria queries are accessed through the
EntityManager.getCriteriaBuilder() API, and executed through the normal
Criteria queries can use parameters, and query hints the same as named queries.
Example dynamic query execution
EntityManager em = getEntityManager(); 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(); ...