Difference between revisions of "EclipseLink/Examples/JPA/2.0/Criteria"

From Eclipsepedia

Jump to: navigation, search
(New page: ===Criteria API (JPA 2.0)=== JPA 2.0 defines a query <i>criteria</i> API to simplify dynamic query creation. With JPQL dynamic queries would require performing string concatenations to bu...)
 
(Criteria API (JPA 2.0))
 
Line 1: Line 1:
===Criteria API (JPA 2.0)===
+
=How to define dynamic queries using the Criteria API=
 
JPA 2.0 defines a query <i>criteria</i> 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.
 
JPA 2.0 defines a query <i>criteria</i> 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.
  
Line 6: Line 6:
 
Criteria queries can use parameters, and query hints the same as named queries.
 
Criteria queries can use parameters, and query hints the same as named queries.
  
====Example dynamic query execution====
+
==Example dynamic query execution==
 
<source lang="java">
 
<source lang="java">
 
EntityManager em = getEntityManager();
 
EntityManager em = getEntityManager();

Latest revision as of 11:47, 30 November 2009

[edit] 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 Query API.

Criteria queries can use parameters, and query hints the same as named queries.

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