EclipseLink/Examples/JPA/2.0/Criteria

From Eclipsepedia

< EclipseLink‎ | Examples‎ | JPA
Revision as of 11:47, 30 November 2009 by James.sutherland.oracle.com (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

Criteria API (JPA 2.0)

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 Query API.

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();
...