Friday, July 13, 2012

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

JPA 2.0

1. JPA

1.1. Overview

The process of mapping Java objects to database tables and vice versa is called "Object-relational mapping" (ORM).
The Java Persistence API (JPA) is one possible approach to ORM. JPA is a specification and several implementations are available. Popular implementations are Hibernate, EclipseLink and Apache OpenJPA. The reference implementation of JPA is EclipseLink.
Via JPA the developer can map, store, update and retrieve data from relational databases to Java objects and vice versa.
JPA permits the developer to work directly with objects rather then with SQL statements. The JPA implementation is typically called persistence provider. JPA can be used in Java-EE and Java-SE applications.
The mapping between Java objects and database tables is defined via persistence metadata. The JPA provider will use the persistence metadata information to perform the correct database operations.
JPA typically defines the metadata via annotations in the Java class. Alternatively the metadata can be defined via XML or a combination of both. A XML configuration overwrites the annotations.
The following description will be based on the usage of annotations.
JPA defines a SQL-like Query language for static and dynamic queries.
Most JPA persistence provider offer the option to create automatically the database schema based on the metadata.

1.2. Entity

A class which should be persisted in a database it must be annotated with javax.persistence.Entity. Such a class is called Entity. JPA will create a table for the entity in your database. Instances of the class will be a row in the table.
All entity classes must define a primary key, must have a non-arg constructor and or not allowed to be final. Keys can be a single field or a combination of fields.
JPA allows to auto-generate the primary key in the database via the @GeneratedValue annotation.
By default, the table name corresponds to the class name. You can change this with the addition to the annotation @Table(name="NEWTABLENAME").

1.3. Persistence of fields

The fields of the Entity will be saved in the database. JPA can use either your instance variables (fields) or the corresponding getters and setters to access the fields. You are not allowed to mix both methods. If you want to use the setter and getter methods the Java class must follow the Java Bean naming conventions. JPA persists per default all fields of an Entity, if fields should not be saved they must be marked with @Transient.
By default each field is mapped to a column with the name of the field. You can change the default name via @Column (name="newColumnName").
The following annotations can be used.

1.4. Relationship Mapping

JPA allows to define relationships between classes, e.g. it can be defined that a class is part of another class (containment). Classes can have one to one, one to many, many to one, and many to many relationships with other classes.
A relationship can be bidirectional or unidirectional, e.g. in a bidirectional relationship both classes store a reference to each other while in an unidirectional case only one class has a reference to the other class. Within a bidirectional relationship you need to specify the owning side of this relationship in the other class with the attribute "mappedBy", e.g. @ManyToMany(mappedBy="attributeOfTheOwningClass".

1.5. Entity Manager

The entity manager javax.persistence.EntityManager provides the operations from and to the database, e.g. find objects, persists them, remove objects from the database, etc. In a JavaEE application the entity manager is automatically inserted in the web application. Outside JavaEE you need to manage the entity manager yourself.
Entities which are managed by an Entity Manager will automatically propagate these changes to the database (if this happens within a commit statement). If the Entity Manager is closed (via close()) then the managed entities are in a detached state. If synchronize them again with the database a Entity Manager provides the merge() method.
The persistence context describes all Entities of one Entity manager.

1.6. Persistence Units

The EntityManager is created by the EntitiyManagerFactory which is configured by the persistence unit. The persistence unit is described via the file "persistence.xml" in the directory META-INF in the source folder. A set of entities which are logical connected will be grouped via a persistence unit. "persistence.xml" defines the connection data to the database, e.g. the driver, the user and the password,


2. Simple Example

2.1. Project and Entity

Create a java Project. Create a folder "lib" and place the required JPA jars and derby.jar into this folder.

package web.com.jpamodel;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class DoSomething{
 @Id
 @GeneratedValue(strategy = GenerationType.IDENTITY)
 private Long i;
 private String a;
 private String b;

 public String getA() {
  return summary;
 }

 public void setA(String A) {
  this.summary = summary;
 }

 public String getB() {
  return description;
 }

 public void setB(String B) {
  this.description = description;
 }


} 

3. Relationship Example

Create a Java project, create again a folder "lib" and place the required JPA jars and derby.jar into this folder.


package web.com.jpamodel;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;

@Entity
public class Family {
 @Id
 @GeneratedValue(strategy = GenerationType.TABLE)
 private int id;
 private String description;

 @OneToMany(mappedBy = "family")
 private final List members = new ArrayList();

 public int getId() {
  return id;
 }

 public void setId(int id) {
  this.id = id;
 }

 public String getDescription() {
  return description;
 }

 public void setDescription(String description) {
  this.description = description;
 }

 public List getMembers() {
  return members;
 }

} 



 /**********************************************************************/

package web.com.jpamodel;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Transient;

@Entity
public class Person {
 @Id
 @GeneratedValue(strategy = GenerationType.TABLE)
 private String id;
 private String firstName;
 private String lastName;

 private Family family;

 private String nonsenseField = "";

 private List jobList = new ArrayList();

 public String getId() {
  return id;
 }

 public void setId(String Id) {
  this.id = Id;
 }

 public String getFirstName() {
  return firstName;
 }

 public void setFirstName(String firstName) {
  this.firstName = firstName;
 }

 // Leave the standard column name of the table
 public String getLastName() {
  return lastName;
 }

 public void setLastName(String lastName) {
  this.lastName = lastName;
 }

 @ManyToOne
 public Family getFamily() {
  return family;
 }

 public void setFamily(Family family) {
  this.family = family;
 }

 @Transient
 public String getNonsenseField() {
  return nonsenseField;
 }

 public void setNonsenseField(String nonsenseField) {
  this.nonsenseField = nonsenseField;
 }

 @OneToMany
 public List getJobList() {
  return this.jobList;
 }

 public void setJobList(List nickName) {
  this.jobList = nickName;
 }

} 

 /***********************************************************************/
package web.com.jpamodel;


import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class Job {
 @Id
 @GeneratedValue(strategy = GenerationType.TABLE)
 private int id;
 private double salery;
 private String jobDescr;

 public int getId() {
  return id;
 }

 public void setId(int id) {
  this.id = id;
 }

 public double getSalery() {
  return salery;
 }

 public void setSalery(double salery) {
  this.salery = salery;
 }

 public String getJobDescr() {
  return jobDescr;
 }

 public void setJobDescr(String jobDescr) {
  this.jobDescr = jobDescr;
 }

}