Monday, March 4, 2013

JPA : Using Criteria API

Using the Criteria API to Create Queries

The Criteria API is used to define queries for entities and their persistent state by creating query-defining objects. Criteria queries are written using Java programming language APIs, are typesafe, and are portable. Such queries work regardless of the underlying data store.

Overview of the Criteria and Metamodel APIs

Similar to JPQL, the Criteria API is based on the abstract schema of persistent entities, their relationships, and embedded objects. The Criteria API operates on this abstract schema to allow developers to find, modify, and delete persistent entities by invoking Java Persistence API entity operations. The Metamodel API works in concert with the Criteria API to model persistent entity classes for Criteria queries.
The Criteria API and JPQL are closely related and are designed to allow similar operations in their queries. Developers familiar with JPQL syntax will find equivalent object-level operations in the Criteria API.
The following simple Criteria query returns all instances of the Car entity in the data source:
            EntityManager em = ...;
            CriteriaBuilder cb = em.getCriteriaBuilder();
            CriteriaQuery cq = cb.createQuery(Car.class);
            Root car= cq.from(Car.class);
            cq.select(car);
            TypedQuery q = em.createQuery(cq);
            List allCars = q.getResultList();
          
            The equivalent JPQL query is:
          
            SELECT c
            FROM Car c

This query demonstrates the basic steps to create a Criteria query:

  1. Use an EntityManager instance to create a CriteriaBuilder object.
  2. Create a query object by creating an instance of the CriteriaQuery interface. This query object's attributes will be modified with the details of the query.
  3. Set the query root by calling the from method on the CriteriaQuery object.
  4. Specify what the type of the query result will be by calling the select method of the CriteriaQuery object.
  5. Prepare the query for execution by creating a TypedQuery instance, specifying the type of the query result.
  6. Execute the query by calling the getResultList method on the TypedQuery object. Because this query returns a collection of entities, the result is stored in a List.
The tasks associated with each step are discussed in detail in this chapter.
To create a CriteriaBuilder instance, call the getCriteriaBuilder method on the EntityManager instance:
CriteriaBuilder cb = em.getCriteriaBuilder();
The query object is created by using the CriteriaBuilder instance:
CriteriaQuery cq = cb.createQuery(Car.class);
The query will return instances of the Pet entity, so the type of the query is specified when the CriteriaQuery object is created to create a typesafe query.
The FROM clause of the query is set, and the root of the query specified, by calling the from method of the query object:
Root pet = cq.from(Car.class);
The SELECT clause of the query is set by calling the select method of the query object and passing in the query root:
cq.select(car);
The query object is now used to create a TypedQuery object that can be executed against the data source. The modifications to the query object are captured to create a ready-to-execute query:
TypedQuery q = em.createQuery(cq);
This typed query object is executed by calling its getResultList method, because this query will return multiple entity instances. The results are stored in a List collection-valued object.
List allCars = q.getResultList();

For Example:

Simple Query

Query query = entityManager.createQuery("from SimpleBean s");
List list = query.getResultList();
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaQuery criteriaQuery = criteriaBuilder.createQuery();
Root from = criteriaQuery.from(SimpleBean.class);
CriteriaQuery select = criteriaQuery.select(from);
TypedQuery typedQuery = entityManager.createQuery(select);
List resultList = typedQuery.getResultList();
assertEqualsList(list, resultList);
 

Simple Query with Order


List expected= entityManager.createQuery("from SimpleBean s order by s.pbyte asc ,s.pint desc")
                                  .getResultList();
 
//...
CriteriaQuery select = criteriaQuery.select(from);
        select.orderBy(criteriaBuilder.asc(from.get("pbyte"))
                        ,criteriaBuilder.desc(from.get("pint")));
TypedQuery typedQuery = entityManager.createQuery(select);
       //...
 

Simple Query with selected fields


Query query = entityManager.createQuery("select s.id,s.pbyte from SimpleBean s ");
List listExpected = query.getResultList();
        //...
CriteriaQuery select = criteriaQuery.multiselect(from.get("id"),from.get("pbyte"));
 
 

Query with single criteria


int arg1 = 20000;
Query query = entityManager.createQuery("from SimpleBean s where s.pint>=:arg1");
query.setParameter("arg1", arg1);
List list = query.getResultList();
 
//...
CriteriaQuery select = criteriaQuery.select(from);
 
Predicate predicate = criteriaBuilder.ge(from.get("pint"), arg1);
criteriaQuery.where(predicate);
//...
 
 

Query with multiple criterias


int arg1 = 20000;
int arg2 = 50000;
Query query = entityManager.createQuery("from SimpleBean s where s.pint>=:arg1 and s.pint<=:arg2");
query.setParameter("arg1", arg1);
query.setParameter("arg2", arg2);
List list = query.getResultList();
 
//..
Predicate predicate1 = criteriaBuilder.ge(from.get("pint"), arg1);
Predicate predicate2 = criteriaBuilder.le(from.get("pint"), arg2);
criteriaQuery.where(criteriaBuilder.and(predicate1, predicate2));
//..
 
 

Query with aggreation (group by)


Query query = entityManager.createQuery("select min(s.pint),s.pbyte from SimpleBean s group by s.pbyte");
 
List listExpected = query.getResultList();
 
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaQuery criteriaQuery = criteriaBuilder.createQuery();
Root from = criteriaQuery.from(SimpleBean.class);
 
Expression minExpression = criteriaBuilder.min(from.get("pint"));
Path pbytePath = from.get("pbyte");
CriteriaQuery select = criteriaQuery.multiselect(minExpression, pbytePath);
 
CriteriaQuery groupBy = select.groupBy(pbytePath);
 
TypedQuery typedQuery = entityManager.createQuery(select);
List listActual = typedQuery.getResultList();
 
 
with the help of:
http://docs.oracle.com/javaee/
http://en.wikibooks.org/wiki/Java_Persistence/Querying

 


No comments:

Post a Comment

Followers