You are on page 1of 56

Introduction to Java Persistence API 2.

0
JPA 2.0| 14-June-2012

Topics
• Introduction to JPA 2.0 • Entity Manager API
• JPA Interfaces. • Relationship mapping.
• JPA configuration. o One to One
• Sample configuration Java SE/EE o Many to One
• Spring Integration o One to Many
• Anatomy of Entity. o Many to Many
• Minimal Entity. • Inheritance Mapping.
• Persistent Identity generation techniques. • JPQL
o AUTO id generation • Criteria API
o Table id generation • JPA Exceptions
o Sequence id generation • References.
• Entity Lifecycle.
• Persistent context.

© COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL 2

Introduction| About JPA 2.0
• Persistence API for operating on POJO entities
• Merger of expertise from TopLink, Hibernate, JDO, EJB vendors and individuals.
• Created as part of EJB 3.0 within JSR 317
• Released Dec 2010 as part of Java EE 6
• “Bootstrap API” can also be used in Java SE (No need of application server)
• Pluggable Container-Provider SPI

• Popular implementations of JPA are:
o Hibernate
o EclipseLink
o OpenJPA

• The Java Persistence API provides Java developers with an object/relational mapping facility for
managing relational data in Java applications. Java Persistence consists of four areas:
o The Java Persistence API
o The query language
o The Java Persistence Criteria API
o Object/relational mapping metadata

© COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL 3

JPA Interfaces
• EntityManagerFactory
o The EntityManagerFactory represents the configuration for a database in your application. We would
typically define one EntityManagerFactory per datastore.
o The EntityManagerFactory is used to create multiple EntityManager instances.

• EntityManager
o EntityManager instance is analogous to a database connection.
o In a multithreaded web application, each thread will have its own EntityManager

• EntityTransaction
o Each EntityManager has a single EntityTransaction, which is required for persisting changes to the underlying
database.
• Query
o EntityManager serves as a factory for generating Query classes.

© COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL 4

JPA Configuration
• JPA requires you to create a META-INF/persistence.xml file.

• In persistence.xml, we can we can optionally configure which classes we want to include for a
given persistence unit. This is mostly useful in multi datastore applications.

• Persistence Provider

o The Java Persistence API has a pluggable Service Provider Interface (SPI) that allows any compliant Java EE
server to communicate with any compliant persistence provider implementation.

o The provider class should implement the ”javax.persistence.spi.PersistenceProvider” interface must be listed
in the provider element.

© COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL 5

persistence.1013/b28221/cfgdepds005.HibernatePersistence</provider> <properties> <property name="javax.sun.com/xml/ns/persistence" xmlns:xsi="http://www.persistence.apache.Sample Configuration | Java SE/EE <persistence xmlns="http://java.user" value="APP"/> <property name="javax.jdbc.Person </class> <provider>org.oracle.jdbc.sun.htm © COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL 6 .sapient.jdbc.ClientDriver"/> <property name="javax.create=true"/> <property name="javax.com/xml/ns/persistence http://java.com/xml/ns/persistence/persistence_2_0.com/cd/B32110_01/web.w3.ejb.domain.hibernate.url" value="jdbc:derby://localhost:1527/EmpServDB.persistence.jdbc.sun.driver" value="org.org/2001/XMLSchema-instance" xsi:schemaLocation = "http://java.0"> <persistence-unit name=“jpaDemo" transaction-type="RESOURCE_LOCAL"/> <class> com.password" value="APP"/> </properties> </persistence> • Refer http://docs.jdbc.persistence.derby.xsd" version="2.

orm.orm.LocalEntityManagerFactoryBean"> <property name="persistenceUnitName" value=“jpaDemo"/> </bean> • LocalContainerEntityManagerFactoryBean for annotation o Configure a datasource and JPA vendor-specific adapters. o Define datasource bean.orm.jpa.jpa.jpa.springframework.JpaTransactionManager" p:entityManagerFactory-ref="entityManagerFactory"/> <tx:annotation-driven mode="aspectj" transaction-manager="transactionManager"/> © COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL 7 .LocalContainerEntityManagerFactoryBean" p:dataSource- ref="dataSource"/> </context:component-scan> o Define Transaction manager <bean id="transactionManager" class="org.Spring Integration • Here are the ways for Spring integration: • LocalEntityManagerFactoryBean uses JPA's Java SE bootstrapping. <bean id="entityManagerFactory" class="org.springframework.springframework. scanning. o Create the LocalContainerEntityManagerFactoryBean <bean id="entityManagerFactory" class="org.

• Take a look at Hibernate configuration properties and the provider class.Exercise • Configure JPA using spring integration technique. • Configure JPA without using persistence. © COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL 8 .xml file.

The no-arg constructor must be public or protected. No methods or persistent instance variables of the entity class may be final. and polymorphic queries. • The entity class must be a top-level class. © COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL 9 . • The entity class must have a no-arg constructor. An enum or interface must not be designated as an entity.Anatomy of an Entity • An entity is a lightweight persistent domain object (POJO). • An entity represents a table in a relational database. • The entity class must be annotated with the Entity annotation. • The entity class must not be final. • The persistent state of an entity is represented by instance variables (transient variables will not be the part of persistent state) • Entities support inheritance. polymorphic associations. and each entity instance corresponds to a row in that table.

….id = id. } © COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL 10 . } …. } public void setId(int id) { this..Minimal Entity Primary key • Must be indicated as an Entity o @Entity annotation on the class • Must have a persistent identifier (primary key) o Primary key can be a compound key as well.. public int getId() { return id. @Entity public class Employee { @Id private int id.

• Implement a test case to retrieve object from datastore using primary key.Exercise • Implement a test case to persist a minimal entity. © COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL 11 .

• Specifying strategy of AUTO indicates that the provider will choose a strategy. o Compound id – multiple fields/properties @Id int id. • Identifiers can be generated in the database by specifying @GeneratedValue on the identifier • 4 pre-defined generation strategies: o AUTO. primary key in database. IDENTITY. @Id String name. • Uniquely identifies entity in memory and in db o Simple id – single field/property @Id int id. SEQUENCE and TABLE @Id @GeneratedValue(strategy=AUTO) private int id.Persistent Identity | Auto identity generation • Identifier (id) in entity. o Embedded id – single field of PK class type @EmbeddedId EmployeePK id. © COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL 12 .

• Easiest way to use table generator @Id @GeneratedValue(strategy=GenerationType. • Fully configured table generator @TableGenerator(name="Emp_Gen". The second column is an integer type that stores the actual id sequence that is being generated. The first column is a string type used to identify the particular generator sequence. valueColumnName="GEN_VAL“initialValue=0. It is the primary key for all the generators in the table. table="ID_GEN".TABLE) private int id.Persistent Identity | Id generation using table • Most flexible and portable way to generate identifiers is to use a database table • An id generation table should have two columns.allocationSize=100)) @Id @GeneratedValue(generator="Emp_Gen") private int id. © COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL 13 . pkColumnName="GEN_NAME".

o In this case. © COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL 14 . no generator is named. so the provider will use a default sequence object of its own choosing.SEQUENCE) private int id. @Id @GeneratedValue(strategy=GenerationType. • Minimal configuration o we are not concerned that it be any particular sequence. sequenceName="Emp_Seq") @Id @GeneratedValue(generator="Emp_Gen") private int id. • Fully configured sequence generator @SequenceGenerator(name="Emp_Gen".Persistent Identity | Id generation using database sequence • A database sequence can be used to generate identifiers when the underlying database supports them.

Exercise • Implement auto Id generation • Implement table id generation. • Implement sequence id generation. © COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL 15 .

but underlying row will be deleted. Not linked to database. but not connected to database • Removed – associated with persistence context. Entity Lifecycle • New – entity is instantiated but not associated with persistence context. • The state of persistent entities is synchronized to the database when the transaction commits new new() refresh() persist() managed remove() persist() removed merge() End of context detached © COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL 16 . Changes get synchronized with database • Detached – has an id. • Managed – associated with persistence context.

• Entities are managed by the entity manager. • An entity manager manages a persistence context and a persistence context is a managed set of entity instances. but are not individually removable (“detached”) • Every persistence context is associated with a persistence unit. • If the persistence context participates in a transaction. the in-memory state of the managed entities will get synchronized to the database.Persistent Context • A persistence context is a set of managed entity instances that exist in a particular data store o Entities keyed by their persistent identity o Only one entity with a given persistent identity may exist in the persistence context o Entities are added to the persistence context. © COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL 17 . • An entity instance is managed means that it is contained within a persistence context.

Persistence Context Persistence Application Context (L2 cache) Entity Manager Entity A Entity C Entity a Entity B Entity b Entities © COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL 18 .

Entity Manager | API • persist() o Insert a new entity instance into the database o Save the persistent state of the entity and any owned relationship references o Entity instance becomes managed • remove() o Delete a managed entity with the given persistent identity from the database • refresh()- o Reload the entity state from the db • merge() o State of detached entity gets merged into a managed copy of the detached entity • find() o Obtain a managed entity instance with a given persistent identity – return null if not found • createQuery() o Create query instance using dynamic JP QL • createNamedQuery() o Create instance for a predefined query • createNativeQuery() o Create instance for an SQL query • contains() o Determine if entity is managed by pc • flush() o Force synchronization of pc to database © COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL 19 .

Relationship Mapping © COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL 20 .

© COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL 21 . A bidirectional relationship has both an owning side and an inverse (non-owning) side. • For one-to-one relationship. the owning side corresponds to the side that contains the corresponding foreign key. one of the following relationship modeling annotations must be applied to the corresponding persistent property or field of the referencing entity: @OneToOne. @OneToMany. • If there is an association between two entities. A unidirectional relationship has only an owning side.Relationship Mapping • Relationships among entities may be o one-to-one o one-to-many o many-to-one o many-to-many. The owning side of a relationship determines the updates to the relationship in the database. @ManyToOne. • Relationships may be bidirectional or unidirectional. @ManyToMany.

REMOVE. EAGER (Lazy means don't load row until the property is retrieved) © COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL 22 . REFRESH • We can declare performance strategy to use with fetching related rows FetchType o LAZY. PERSIST.Relationship Mapping 2 • JPA supports cascading updates/deletes • CascadeType o ALL. MERGE.

} } © COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL 23 .. • Entity A is specified as the owner of the relationship. Example: @Entity public class Person{ • Entity A is mapped to a table named A.EAGER) @Entity //default public class PersonDetail{ @JoinColumn(name="pdetail_fk") private Person person..AL L. personDetail. }. return person. fetch=FetchType. }.Relationship Mapping | One To One Assumptions: • Entity A references a single instance of Entity B. @OneToOne(cascade=CascadeType. public PersonDetail @OneToOne(mappedBy="personDetail") getPersonDetail() { public Person getPerson() { return personDetail.. • Entity B references a single instance of Entity A. private PersonDetail • Entity B is mapped to a table named B.. • Table A contains a foreign key to table B.

Exercise • Implement One to One mapping among person and person details class • Use bi-directional relationship © COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL 24 .

..Relationship Mapping | Many To One @Entity public class Student { Student @Id studentId College_id int studentId.. } } • Many side will own the relationship so join column annotation will be put on many side. @ManyToOne College @JoinColumn ID .. (name=“College_id”) College college. © COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL 25 . .

. } © COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL 26 . int id..Relationship Mapping | One To Many • For bi-directional relationship use “mappedBy” attribute... @Entity public class College { College @Id ID .. College_id @Id int id.. Set<Student> students. @OneToMany(mappedBy=“college”) . } @Entity Student public class Students { ID .. @ManyToOne College college.. .

Exercise • Implement One to Many mapping among student and college class • Use bi-directional relationship © COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL 27 .

© COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL 28 .. inverseJoinColumns={@JoinColumn(name="event_id")}) List<Event> events. joinColumns=@JoinColumn(name="event_id")}. inverseJoinColumns=@JoinColumn(name="delegate_id“)}) List<Delegate> delegates. @ManyToMany @JoinTable(name=“JOIN_DELEGATE_EVENT". } @Entity public class Delegate { .. @ManyToMany @JoinTable(name="JOIN_DELEGATE_EVENT".. joinColumns={@JoinColumn(name="delegate_id")}..Relationship Mapping | Many to Many @Entity public class Event { .

Relationship Mapping | Many to Many EVENT_ID EVENT_NAME DELEGATE_ID DELEGATE_NAME EVENT DELEGATE EVENT_ID DELEGATE_ID JOIN_DELEGATE_EVENT © COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL 29 .

• An event can be attended by multiple delegates. • Use bi-directional relationship © COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL 30 .Exercise • Implement Many to Many mapping among Event and Delegate class. • A delegate can attend multiple events.

Relationship Mapping | Inheritance mapping • An important capability of the JPA is its support for inheritance and polymorphism • Entities can inherit from other entities and from non-entities • The @Inheritance annotation identifies a mapping strategy: o SINGLE_TABLE o JOINED o TABLE_PER_CLASS © COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL 31 .

{STRING.Inheritance Mapping | Single table @Entity @Inheritance(strategy=InheritanceType. . CHAR. .all classes in the hierarchy are mapped to a single table in the database • Discriminator column .contains a value that identifies the subclass • Discriminator type . discriminatorType=DiscriminatorType.STRING) @DiscriminatorValue(value=“Project") public class Project { . INTEGER} • Discriminator value .value entered into the discriminator column for each entity in a class hierarchy © COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL 32 . .SINGLE_TABLE) @DiscriminatorColumn(name="DISC". } @Entity @DiscriminatorValue(name=“Module") public class Module extends Project { . } • SINGLE_TABLE strategy . .

Inheritance mapping | Table per class @Entity @Inheritance(strategy=InheritanceType. . } @Entity public class Task extends Module { . } • One cannot use AUTO for primary key generation strategy with conjunction with table per concrete class" inheritance. . } @Entity public class Module extends Project { . . . . . © COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL 33 . because in such a case the identity column must be present in each table and its values must be mutually exclusive.TABLE_PER_CLASS) public class Project { .

. • In joined inheritance a table is defined for each class in the inheritance hierarchy to store only the local attributes of that class. . } @Entity public class Module extends Project { . . } @Entity public class Task extends Module { . .JOINED) public class Project { . @Entity @Inheritance(strategy=InheritanceType. Each table in the hierarchy must also store the object's id (primary key). . } © COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL 34 . . which is only defined in the root class.Inheritance mapping | Join Table • Joined inheritance is the most logical inheritance solution because it mirrors the object model in the data model.

the "wider" the mapped table gets. since a wide or deep inheritance hierarchy will result in tables with many mostly-empty columns. since it never requires a join to retrieve a persistent instance from the database. This may have undesirable consequence on the database size. © COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL 35 . meaning the schema with the least spurious or redundant data. • JOINED • Advantage: o Using joined subclass tables results in the most normalized database schema. • TABLE_PER_CLASS • Advantage : o The table-per-class strategy is very efficient when operating on instances of a known class(no joins). • Disadvantage: o The joined strategy is often the slowest of the inheritance models. in that for every field in the entire inheritance hierarchy. a column must exist in the mapped table. • Disadvantage: o The larger the inheritance model gets.Inheritance Mapping | Summary • SINGLE_TABLE • Advantage: o Single table inheritance mapping is the fastest of all inheritance models.

Exercise • Implement the below classes hierarchy using all the inheritance techniques we studied. Project Module Task • Use bi-directional relationship © COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL 36 .

JPA 2.0 | Queries Queries and Criteria API © COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL 37 .

• In addition to retrieving objects (SELECT queries). • JPQL lets you define queries using one of the following three statements: SELECT. • JPQL eliminates the need for you to use JDBC API from your Java code—the container does all this work for you behind the scenes. • It is heavily inspired by SQL.Queries using JPQL | Introduction • Allows writing of queries that are portable across data stores (databases). • Standard hooks for vendor-specific hints • Query instances are obtained from factory methods on EntityManager © COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL 38 . while the latter deals directly with relational data. but operate against JPA entity objects rather than directly with database tables. UPDATE. or DELETE. JPQL supports bulk UPDATE and DELETE queries • The main difference between JPQL and SQL lies in that the former deals with JPA entities. • The Java Persistence Query Language (JPQL) is a platform-independent object-oriented query language defined as part of the Java Persistence API specification. and its queries resemble SQL queries in syntax.

any changes made to entity objects will be reflected the very next time when a SELECT query is made o COMMIT .the persistence engine may only update all the state of the entities during the database COMMIT © COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL 39 .Queries | Introduction Query API: • getResultList() – execute query returning multiple results • getSingleResult() – execute query returning single result • executeUpdate() – execute bulk update or delete • setFirstResult() – set the first result to retrieve • setMaxResults() – set the maximum number of results to retrieve • setParameter() – bind a value to a named or positional parameter • setHint() – apply a vendor-specific hint to the query • setFlushMode()– apply a flush mode to the query when it gets run o Two modes of flushing query objects o AUTO (default) and COMMIT o AUTO .

executeUpdate() • Query may be compiled/checked at creation time or when executed • Maximal flexibility for query definition and execution public List findAll(String entityName){ return entityManager. getSingleResult().createQuery( "select e from " + entityName + " e") .getResultList(). if “Account” was passed in then JP QL string would be: “select e from Account e” © COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL 40 .Dynamic Queries • Use createQuery() factory method at runtime and pass in the JP QL query string • Use correct execution method getResultList(). } • Return all instances of the given entity type • JP QL string composed from entity type. For example.setMaxResults(100) .

name LIKE ?1”) .setParameter(integer position. Positional Parameters • Positional parameters are prefixed with a question mark (?) & number of the parameter in the query • To set parameter values use method: o Query. Object value) public List findWithName(String name) { return em.setParameter(1.getResultList(). name) . } © COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL 41 .createQuery( “SELECT c FROM Customer c WHERE c.

setParameter("custName". } © COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL 42 .getResultList(). name) .setParameter(String name. Named Parameters • Named parameters are parameters in a query that are prefixed with a colon (:) • To bound parameter to an argument use method: o Query. Object value) public List findWithName(String name) { return em.createQuery( "SELECT c FROM Customer c WHERE c.name LIKE :custName") .

.getResultList().id = :custId= :custId order order by s. } } • Return all sales for a given customer © COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL 43 .salesDate") by s.customer.findByCustId".salesDate") publicpublic List findSalesByCustomer(Customer List findSalesByCustomer(Customercust) { cust) { returnreturn entityManager.getId()) cust. @NamedQuery(name="Sale.id s.createNamedQuery( "Sale.setParameter("custId". query="select query="select s fromsSale froms Sale s wherewhere s. cust.findByCustId") "Sale.createNamedQuery( entityManager.customer.findByCustId".getId()) . .Named Queries • Use createNamedQuery() factory method at runtime and pass in the query name • Query must have already been statically defined either in an annotation or XML • Query names are “globally” scoped • Provider has opportunity to precompile the queries and return errors at deployment time • Can include parameters and hints in static query definition @NamedQuery(name="Sale.getResultList().findByCustId") .setParameter("custId".

com.createNativeQuery( "SELECT o.id) AND (i.quantity.class).acme.item = i.name = 'widget')".id. Native Queries • Queries may be expressed in native SQL • Use when you need to use native SQL of the target database • Can call stored procedures using "call procname" syntax Query q = em.item " + "FROM Order o. o. o. © COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL 44 .Order. Item i " + "WHERE (o.

© COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL 45 .createQuery( “SELECT C FROM CUSTOMER WHERE C. then EntityNotFoundException is returned • If more than one matches occur during query execution a run-time exception NonUniqueResultException will be thrown Query singleSelectQuery = entityManager.ID = ‘ABC-123’”). Query Operations – Single Result • A query that returns a single entity object • If the match wasn’t successful.getSingleResult(). Customer custObj = singleSelectQuery.

o A query for persistent Java™ objects is typesafe if a compiler can verify it for syntactic correctness. o the Java compiler has no way to detect such an error.. String jpql = "select p from Person where p.age > 20".createQuery(jpql). The correct syntax for the second line is : o String jpql = "select p from Person p where p.age > 20".Criteria API | Introduction • Dynamic.0) introduces the Criteria API. © COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL 46 . which brings the power of typesafe queries to Java applications for the first time and provides a mechanism for constructing queries dynamically at run time. but will fail at run time because the JPQL query string is syntactically incorrect.0. Query query = em. • Above code will compile happily. List result = query. typesafe queries in JPA 2.getResultList().. • What's wrong with this JPQL query? o Consider below example EntityManager em = .. o Java Persistence API (JPA 2.

" It is similar to the FROM clause of a JPQL or SQL query.gt(p. • Line 5 constructs a Predicate.get(Person_.. CriteriaBuilder qb = em. © COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL 47 .from(Person. A predicate is constructed by the CriteriaBuilder • Line 6 sets the predicate on the CriteriaQuery as its WHERE clause. CriteriaBuilder is the factory for CriteriaQuery. List<Person> result = q. Root<Person> p = c. 5. • Line 1. 8.getCriteriaBuilder().getResultList(). EntityManager em = . 6. 2. Root is a query expression that denotes the extent of a persistent entity. EntityManager creates an instance CriteriaBuilder. c. o As a result. the CriteriaQuery is set to query from Person. The generic type argument declares the type of result this CriteriaQuery will return upon execution.createQuery(c).Criteria API Path expression(Meta • Basic steps of writing criteria query. Predicate condition = qb.where(condition). the CriteriaBuilder factory constructs a CriteriaQuery instance.class).class). Predicate is another common form of query expression that evaluates to either true or false. 7.class.createQuery(Person. 3.age). 20). root<Person> instance p is returned. CriteriaQuery<Person> c = qb. • In line 3. TypedQuery<Person> q = em. • In line 4.2 : Get entity manager. 4.. model api (not covered)) 1. Root<T> essentially says: "Evaluate this query across all instances of type T.

• CriteriaQuery is transferred to an executable query with its type information preserved so that the elements of the selected list can be accessed without any run-time casting. which is equivalent to a FROM clause. • CriteriaBuilder is the factory for CriteriaQuery and query expressions of all sorts. A few typical expressions are: o Root<T>. © COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL 48 . o Predicate. it is declared as interface Predicate extends Expression<Boolean>.Criteria API • The query expressions are generically typed. (In fact. Root<T> is a special Path<T> with no parent. WHERE. which denotes a persistent attribute navigated from a Root<?> expression. and ORDER BY in a traditional string-based query language. • CriteriaQuery is a tree of query-expression nodes that are used to specify query clauses such as FROM.) o Path<T>. which evaluates to a Boolean value of true or false.

Conditional Method Description equal Tests whether two expressions are equal notEqual Tests whether two expressions are not equal gt Tests whether the first numeric expression is greater than the second numeric expression ge Tests whether the first numeric expression is greater than or equal to the second numeric expression lt Tests whether the first numeric expression is less than the second numeric expression le Tests whether the first numeric expression is less than or equal to the second numeric expression between Tests whether the first expression is between the second and third expression in value like Tests whether the expression matches a given pattern • Compound Predicate Methods in the CriteriaBuilder Interface Method Description and A logical conjunction of two Boolean expressions or A logical disjunction of two Boolean expressions not A logical negation of the given Boolean expression © COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL 49 .Criteria API | Methods in the CriteriaBuilder Interface • Expression Methods in the CriteriaBuilder Interface.

value("Y"). Path<String> name = owner. • where() predicate in CriteriaQuery.value("X").in(name). • Complex predicates | Multivalued expression in CriteriaQuery.createQuery(Account.get(Person_. cb.class).select(cb.class). Root<Account> account = c.class).avg(a.from(Account.'Z')".createQuery(Double.value("Z")).balance>100 and a.balance))).from(Account.lessThan(balance). CriteriaQuery<Account> c = cb. c.owner. 200))). © COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL 50 .createQuery(Account.get(Account_. Path<Person> owner = account.avg(a. • Equivalent JPQL "select a from Account a where a. • JPQL : "select a from Account a where a.class).from(Account.get(Account_.class).createQuery(Double. Path<Integer> balance = account.get(Account_. 100).balance))).balance) from Account a". Root<Account> c.Criteria API |Examples • Functional expression in CriteriaQuery CriteriaQuery<Double> c c= = CriteriaQuery<Double> cb.class).name). • An equivalent JPQL query would be: o String jpql = "select avg(a.balance).where(cb. Root<Account> aa==c. c.balance<200".'Y'.greaterThan(balance. CriteriaQuery<Account> c = cb.class). c.and (cb. Root<Account> account = c.where(cb.name in ('X'.from(Account. c. cb.class).select(cb.get(Account_.owner).

orders). • The original attribute is of type java.Criteria API |Join • CriteriaQuery expresses joining two entities by typed join expressions • A typed join expression has two type parameters: the type you are joining from and the bindable type of the attribute being joined. Status.class). SetJoin<Customer. CriteriaQuery<Customer> q = cb.util. you need to express this by an expression that joins Customer to PurchaseOrders.DELIVERED) .class).status). • For example.from(Customer.Set.createQuery(Customer. © COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL 51 . Predicate p = cb.equal(o. if you want to query for the Customers whose one or more PurchaseOrder(s) are not delivered yet.Set<PurchaseOrder>.Set.join(Customer_.negate(). where Customer has a persistent attribute named orders of type java. • SetJoin is a specialized Join for an attribute of declared type java. • The join expression created from the root expression c and the persistent Customer. the resultant join expression is SetJoin. PurchaseOrder> o = c. Root<Customer> c = q.util.get(PurchaseOrder_.util.orders attribute.

setParameter("age". 20). List<Person> result = q. 20).getResultList(). TypedQuery<Person> q = em.age). • The parameter expression is created with explicit type information to be an Integer and is directly used to bind a value of 20 to the executable query. c.class). ParameterExpression<Integer> age = qb. So a better way to write the query is to use a named parameter: o String jpql = "select p from Person p where p.parameter(Integer.createQuery(jpql). it is not a good practice.createQuery(c).getResultList(). © COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL 52 .setParameter(age. • A parameterized query binds the value of the parameter before the query execution: o Query query = em.where(condition).get(Person_. o List result = query.age > :age".Criteria API | Using parameters • Though queries are often written with constant literals. age). The good practice is to parameterize a query.gt(p. Predicate condition = qb. and reused. cached. which allows the query to be parsed or prepared only once.

• The CriteriaQuery. © COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL 53 .groupBy(pet. cq.Criteria API • Grouping Results o The CriteriaQuery. By calling the having method.get(Pet_.createQuery(Pet.class).color)).value("blonde")).color)).get(Pet_.createQuery(Pet.class).groupBy(pet.having method is used in conjunction with groupBy to filter over the groups.class).class).value("brown").groupBy method partitions the query results into groups.from(Pet. These groups are set by passing an expression to groupBy: CriteriaQuery<Pet> cq = cb.in(pet.get(Pet_. The having method takes a conditional expression as a parameter. Root<Pet> pet = cq.color)). cq. Root<Pet> pet = cq. the query result is restricted according to the conditional expression: CriteriaQuery<Pet> cq = cb. • This query returns all Pet entities and groups the results by the pet’s color. cq.from(Pet.having(cb.

persistence package are self-explanatory © COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL 54 . JPA exceptions • All exceptions are unchecked • Exceptions in javax.

References • http://www.ibm.0) • http://blog.xebia.com/developerworks/java/library/j-typesafejpa/ • http://docs.oracle.com/2009/03/09/jpa-implementation-patterns-data-access-objects/ • JSR 317 • Open JPA © COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL 55 .com/javaee/6/tutorial/doc/gjitv.html • Pro JPA 2 (Mastering the Java Persistence API 2.

Thank You! © COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL 56 .