SlideShare a Scribd company logo
JPA 2.1
JSR-338 Specification
Why JPA ?
 Java Persistence API (JPA), was introduced
into the platform to bridge the gap between
object-oriented domain models and relational
database systems
 API is part of javax.persistence.* package
distributed by different vendors hibernate-jpa-
2.1-api.jar
Jpa 2.1 Application Development
JPA Terminology
 Entity: It is nothing but a java representation of the database
table that should have characteristics like persist ability, identity,
transactional and granularity.
 Persistence Unit: Configuration of Entities and DB access
information. (persistence.xml file)
 EntityManagerFactory: Factory of Entity Managers which we
can create by passing Persistence Unit.
 EntityManager: Different API calls performed on entities are
managed by the single interface called EntityManager.
 PersistenceContext: Set of entities which are managed by the
entity manager are called persistence context.
 Persistence Provider: Provides underlying implementation to
the APIs. (hibernate, eclipse link etc..)
Jpa 2.1 Application Development
Characteristics of an Entity
An entity class must follow these requirements.
 The class must be annotated with the javax.persistence.Entity annotation.
 The class must have a public or protected, no-argument constructor. The
class may have other constructors.
 The class must not be declared final. No methods or persistent instance
variables must be declared final.
 If an entity instance is passed by value as a detached object, such as
through a session bean’s remote business interface, the class must
implement the Serializable interface.
 Entities may extend both entity and non-entity classes, and non-entity
classes may extend entity classes.
 Persistent instance variables must be declared private, protected, or
package-private and can be accessed directly only by the entity class’s
methods. Clients must access the entity’s state through accessor or
business methods.
Persistence UNIT and Context
 A persistence unit is a named configuration of entity
classes.
 A persistence context is a managed set of entity
instances.
 Every persistence context is associated with a
persistence unit, restricting the classes of the managed
instances to the set defined by the persistence unit.
 Saying that an entity instance is managed means that it
is contained within a persistence context and it can be
acted upon by an entity manager. It is for this reason
that we say that an entity manager manages a
persistence context.
 The entity manager type determines the lifetime of a
persistence context
Entity Manager types
 Container Managed Entity Managers: Lifecycle of the
entity manager managed by the container.
@PersistenceContext(unitName="MysqlPU")
EntityManager entityManager;
 Transaction-scoped: This means that the persistence
contexts managed by the entity manager are scoped by the
active JTA transaction, ending when the transaction is
complete.
 Extended: persistence context of an extended entity
manager will last for the entire length of the conversation of
service (ex: stateful session bean)
 Application Managed Entity Manager : application will
manages the lifecycle of the entity manager.
final EntityManagerFactory emf =
Persistence.createEntityManagerFactory("MysqlPU");
final EntityManager em = emf.createEntityManager();
Transaction Managers
 There are two types of transaction managers supported
by the JPA
 Resource Local : native transactions of the JDBC drivers
that are referenced by a persistence unit.
 JTA: transactions of the Java EE server, supporting multiple
participating resources, transaction lifecycle management,
and distributed XA transactions.
 Container-managed entity managers always use JTA
transactions, while application-managed entity managers
can use either type.
 Because JTA is typically not available in Java SE
applications, the provider needs to support only resource-
local transactions in that environment.
 The default and preferred transaction type for Java EE
applications is JTA. propagating persistence contexts with
JTA transactions is a major benefit to enterprise
persistence applications.
Container Managed VS Application Managed EntityManager
Container Managed EntityManager
@PersistenceContext
EntityManager em;
Application Managed EntityManager
@PersistenceUnit
EntityManagerFactory emf;
Ref: http://piotrnowicki.com/2012/11/types-of-
entitymanagers-application-managed-entitymanager/
Extended Vs Transactional Scoped
 This feature tells us if the EntityManager’s operations might span
across multiple transactions. By default the Transactional
Persistence Context is used which means that all changes are
flushed and all managed entities become detached when the
current transaction commits.
 The extended scope is available only for Stateful EJBs; it makes
perfectly sense as the SFSBs can save the state, so end of one
business method doesn’t necessary means the end of the
transaction.
 With the SLSB the story is different – we have business method
that must end when the business method finishes because in
next invocation we don’t have an idea which EJB instance we’ll
end in. One method = one transaction; only transactional-scoped
EntityManager is allowed for SLSB.
NOTE: Extended and transaction scoped PersistenceContext are
allowed only in case of container-managed EntityManagers.
JPQL (Java Persistence query Language)
 It is similar to SQL queries but it refers Entity
names instead of table names.
@Entity(name="Employee")
@Table(name = "employee_tbl")
public class EmployeeEntity { }
JPQL: SELECT e FROM Employee e;
QUERY PARAMETERS
NOTATION
 POSITIONAL PARAMETERS
final Query positionalParamQuery =
em.createQuery("SELECT e FROM Employee e WHERE
e.id>?1", EmployeeEntity.class);
positionalParamQuery.setParameter(1, 1600l);
 NAMED PARAMETERS
final Query namedParameterQuery =
em.createQuery("SELECT e FROM Employee e WHERE
e.id>=:id", EmployeeEntity.class);
namedParameterQuery.setParameter("id", 1700l);
Named Queries (Recommended)
Persistence providers will often take steps to
precompile JPQL named queries to SQL as part of
the deployment or initialization phase of an
application
@Entity(name = "Employee")
@Table(name = "employee_tbl")
@NamedQuery(name = "employeeById", query = "SELECT e
FROM Employee e WHERE e.id=:id")
public class EmployeeEntity {}
final Query namedQuery =
em.createNamedQuery("employeeById");
namedQuery.setParameter("id", 1801l);
Query Hints AND ADVANCED QUERY
Query hints are the JPA extension point for
query features. A hint is simply a string name
and object value. Hints allow features to be
added to JPA without introducing a new API.
 namedQuery.setHint("javax.persistence.query.ti
meout", 1);
 query.setHint("org.hibernate.cacheable",
Boolean.TRUE);
Advanced Query:
SELECT NEW
com.innominds.dto.Employee(e.id,e.name,e.salary,e.join
Date) FROM Employee e
INHERITANCE AND
POLYMORPHISM
 SELECT p FROM Project p WHERE p.employees IS
NOT EMPTY
 SELECT p FROM Project p WHERE TYPE(p) =
DesignProject OR TYPE(p) = QualityProject
 INNER JOIN QUERY EXAMPLE
SELECT pFROM Employee e JOIN e.phones p
SUB QUERIES
 SELECT e FROM Employee e WHERE
e.salary = (SELECT MAX(emp.salary) FROM
Employee emp)
COLLECTION EXPRESSION
 SELECT e FROM Employee e WHERE
e.directs IS NOT EMPTY
 SELECT m FROM Employee m WHERE
(SELECT COUNT(e) FROM Employee e
WHERE e.manager = m) > 0
MEMBER OF
 The MEMBER OF operator and its negated
form NOT MEMBER OF are a shorthand way
of checking whether an entity is a member of
a collection association path.
SELECT e FROM Employee e WHERE e
MEMBER OF e.directs
Enabling SECOND LEVEL CACHE IN 4.0 (3.3.x) or higher
 Hibernate has its own EHCache implementation from
version 4 onwards.
Add below properties to configuration
<property name="hibernate.cache.region.factory_class"
value="org.hibernate.cache.ehcache.EhCacheRegionFa
ctory"/>
<property
name="hibernate.cache.use_second_level_cache"
value="true" />
<property name="hibernate.cache.use_query_cache"
value="true" />
<property name="hibernate.generate_statistics"
value="true" />
Second LEVEL CACHE MODES
Second level cache can be controller using property
"javax.persistence.sharedCache.mode".
Following values are allowed
 ALL: All entity data is stored in the 2nd level cache
 NONE: No data is cached
 ENABLE_SELECTIVE: Entities marked with @Cachable
are cached
 DISABLE_SELECTIVE: All entities except
@Cachable(false) are cached
 UNSPECIFIED: Caching behavior is not specified,
Persistence provider’s default caching behavior is used.
final Properties additionalConfig = new Properties();
additionalConfig.put("javax.persistence.sharedCache.mode",
"DISABLE_SELECTIVE");
Cache Retrieval and Store Modes
 When the second level cache is enabled for a persistence
unit, we’re now able fine-tune the caching behavior by
setting retrieval-mode and store-mode-properties at
persistence context level or for each entity-manager
operation or query level by setting below properties.
 Retrieve Mode can be set using below property
javax.persistence.cache.retrieveMode
 Store Mode can be set using below property
javax.persistence.cache.storeMode
Retrieve MODES
 Following options are available for Retrieve mode
 BYPASS: The cache is bypassed and a call to the
database is used to retrieve the data.
 USE: If the data is available in the cache, it is read
from this location, else it is fetched from the database.
EX:
config.put("javax.persistence.cache.retrieveMode",
CacheRetrieveMode.USE);
CACHE STORE MODES
 Following options are available for store mode
 BYPASS: Don’t put anything into the cache
 REFRESH: Data is put/updated in the cache
when read and committed into the database a
refresh enforced
 USE: Data is put/updated in the cache when
read and committed into the database
Container Managed EntityManager
 To demonstrate this scenario I used spring
container to create EntityManagerFactory which
reads the configuration from persistence.xml file.
@Bean(name = "entityManagerFactory")
public EntityManagerFactory entityManagerFactory() {
final LocalContainerEntityManagerFactoryBean em = new
LocalContainerEntityManagerFactoryBean();
em.afterPropertiesSet();// IMP
return em.getObject();
}
NOTE: full java configuration without using persistence.xml
also possible please refer the github source code link in the
next slide.
 Write a Dao class and annotate
EntityManager as shown below
@Repository("personDao")
@Transactional(propagation = Propagation.REQUIRED)
public class PersonDao {
@PersistenceContext
private EntityManager entityManager;
… write your business methods here
}
NOTE: Working code available below location:
https://github.com/Innominds-jee/jpa-cm-training.git
Distributed Transactions using JTA
 https://www.javacodegeeks.com/2013/07/spring-
jta-multiple-resource-transactions-in-tomcat-with-
atomikos-example.html
 https://www.atomikos.com/Documentation/Hiberna
teThreeStandalone
 http://www.careerride.com/JTS-advantages-of-
JTA-over-JTS.aspx
 https://spring.io/blog/2011/08/15/configuring-
spring-and-jta-without-full-java-ee/
 http://www.javaworld.com/article/2077714/java-
web-development/xa-transactions-using-
spring.html
 http://www.byteslounge.com/tutorials/spring-
jta-multiple-resource-transactions-in-tomcat-
with-atomikos-example

More Related Content

What's hot (20)

PPT
jpa-hibernate-presentation
John Slick
 
PPTX
JPA For Beginner's
NarayanaMurthy Ganashree
 
PDF
Introduction to JPA and Hibernate including examples
ecosio GmbH
 
PDF
JPA and Hibernate
elliando dias
 
PPTX
Introduction to jQuery
Collaboration Technologies
 
PPTX
Евгений Капинос "Advanced JPA (Java Persistent API)"
Anna Shymchenko
 
PPT
Jpa
Manav Prasad
 
PPT
hibernate with JPA
Mohammad Faizan
 
PPTX
Hibernate
Prashant Kalkar
 
PPTX
Configuring jpa in a Spring application
Jayasree Perilakkalam
 
PPTX
Hibernate in Action
Akshay Ballarpure
 
PPT
Hibernate Tutorial
Ram132
 
PPS
Java Hibernate Programming with Architecture Diagram and Example
kamal kotecha
 
PPTX
Spring data jpa
Jeevesh Pandey
 
PPT
ORM Concepts and JPA 2.0 Specifications
Ahmed Ramzy
 
PDF
Hibernate Presentation
guest11106b
 
PDF
Introduction to Datastore
Software Park Thailand
 
PPT
Hibernate presentation
Manav Prasad
 
PPT
Java persistence api
Luis Goldster
 
DOC
Hibernate tutorial for beginners
Rahul Jain
 
jpa-hibernate-presentation
John Slick
 
JPA For Beginner's
NarayanaMurthy Ganashree
 
Introduction to JPA and Hibernate including examples
ecosio GmbH
 
JPA and Hibernate
elliando dias
 
Introduction to jQuery
Collaboration Technologies
 
Евгений Капинос "Advanced JPA (Java Persistent API)"
Anna Shymchenko
 
hibernate with JPA
Mohammad Faizan
 
Hibernate
Prashant Kalkar
 
Configuring jpa in a Spring application
Jayasree Perilakkalam
 
Hibernate in Action
Akshay Ballarpure
 
Hibernate Tutorial
Ram132
 
Java Hibernate Programming with Architecture Diagram and Example
kamal kotecha
 
Spring data jpa
Jeevesh Pandey
 
ORM Concepts and JPA 2.0 Specifications
Ahmed Ramzy
 
Hibernate Presentation
guest11106b
 
Introduction to Datastore
Software Park Thailand
 
Hibernate presentation
Manav Prasad
 
Java persistence api
Luis Goldster
 
Hibernate tutorial for beginners
Rahul Jain
 

Similar to Jpa 2.1 Application Development (20)

PPT
test for jpa spring boot persistence hehe
AdePutraNurcholikSan
 
PDF
Jpa
vantinhkhuc
 
ODP
Jpa buenas practicas
fernellc
 
PPTX
Jakarta Persistence (JPA) - Web Technologies
ssuser0562f1
 
PPTX
JPA Entity Manager.pptx
Mohd Ashif Ali
 
DOCX
Ecom lec4 fall16_jpa
Zainab Khallouf
 
PDF
Spring Boot Tutorial Part 2 (JPA&Hibernate) .pdf
abdelr7man3mad2004
 
PDF
Java Persistence API
Ilio Catallo
 
PPT
Java Persistence API (JPA) - A Brief Overview
Craig Dickson
 
ODP
Working with jpa
Ondrej Mihályi
 
PDF
Lecture 9 - Java Persistence, JPA 2
Fahad Golra
 
PDF
Understanding
Arun Gupta
 
PDF
Using the latest Java Persistence API 2.0 features
Arun Gupta
 
PDF
2014 Pre-MSc-IS-3 Persistence Layer
andreasmartin
 
PPT
Entity Manager
patinijava
 
PPT
Ejb6
patinijava
 
PPTX
Jpa 2.0 in java ee 6 part ii
Lars Lemos
 
PPT
Slice: OpenJPA for Distributed Persistence
Pinaki Poddar
 
PPT
Jpa basics
Balaji Vericharla
 
PPT
Al rihieli persistence
Jhonny Villarroel
 
test for jpa spring boot persistence hehe
AdePutraNurcholikSan
 
Jpa buenas practicas
fernellc
 
Jakarta Persistence (JPA) - Web Technologies
ssuser0562f1
 
JPA Entity Manager.pptx
Mohd Ashif Ali
 
Ecom lec4 fall16_jpa
Zainab Khallouf
 
Spring Boot Tutorial Part 2 (JPA&Hibernate) .pdf
abdelr7man3mad2004
 
Java Persistence API
Ilio Catallo
 
Java Persistence API (JPA) - A Brief Overview
Craig Dickson
 
Working with jpa
Ondrej Mihályi
 
Lecture 9 - Java Persistence, JPA 2
Fahad Golra
 
Understanding
Arun Gupta
 
Using the latest Java Persistence API 2.0 features
Arun Gupta
 
2014 Pre-MSc-IS-3 Persistence Layer
andreasmartin
 
Entity Manager
patinijava
 
Jpa 2.0 in java ee 6 part ii
Lars Lemos
 
Slice: OpenJPA for Distributed Persistence
Pinaki Poddar
 
Jpa basics
Balaji Vericharla
 
Al rihieli persistence
Jhonny Villarroel
 
Ad

Recently uploaded (20)

PDF
How to Hire AI Developers_ Step-by-Step Guide in 2025.pdf
DianApps Technologies
 
PDF
MiniTool Partition Wizard 12.8 Crack License Key LATEST
hashhshs786
 
PPTX
Foundations of Marketo Engage - Powering Campaigns with Marketo Personalization
bbedford2
 
PPTX
Home Care Tools: Benefits, features and more
Third Rock Techkno
 
PPTX
Milwaukee Marketo User Group - Summer Road Trip: Mapping and Personalizing Yo...
bbedford2
 
PPTX
Empowering Asian Contributions: The Rise of Regional User Groups in Open Sour...
Shane Coughlan
 
PDF
MiniTool Partition Wizard Free Crack + Full Free Download 2025
bashirkhan333g
 
PPTX
Help for Correlations in IBM SPSS Statistics.pptx
Version 1 Analytics
 
PPTX
Customise Your Correlation Table in IBM SPSS Statistics.pptx
Version 1 Analytics
 
PDF
Driver Easy Pro 6.1.1 Crack Licensce key 2025 FREE
utfefguu
 
PDF
4K Video Downloader Plus Pro Crack for MacOS New Download 2025
bashirkhan333g
 
PPTX
OpenChain @ OSS NA - In From the Cold: Open Source as Part of Mainstream Soft...
Shane Coughlan
 
PDF
Download Canva Pro 2025 PC Crack Full Latest Version
bashirkhan333g
 
PDF
Automate Cybersecurity Tasks with Python
VICTOR MAESTRE RAMIREZ
 
PDF
Open Chain Q2 Steering Committee Meeting - 2025-06-25
Shane Coughlan
 
PPTX
Change Common Properties in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
PDF
AOMEI Partition Assistant Crack 10.8.2 + WinPE Free Downlaod New Version 2025
bashirkhan333g
 
PPTX
Comprehensive Risk Assessment Module for Smarter Risk Management
EHA Soft Solutions
 
PDF
Technical-Careers-Roadmap-in-Software-Market.pdf
Hussein Ali
 
PPTX
Coefficient of Variance in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
How to Hire AI Developers_ Step-by-Step Guide in 2025.pdf
DianApps Technologies
 
MiniTool Partition Wizard 12.8 Crack License Key LATEST
hashhshs786
 
Foundations of Marketo Engage - Powering Campaigns with Marketo Personalization
bbedford2
 
Home Care Tools: Benefits, features and more
Third Rock Techkno
 
Milwaukee Marketo User Group - Summer Road Trip: Mapping and Personalizing Yo...
bbedford2
 
Empowering Asian Contributions: The Rise of Regional User Groups in Open Sour...
Shane Coughlan
 
MiniTool Partition Wizard Free Crack + Full Free Download 2025
bashirkhan333g
 
Help for Correlations in IBM SPSS Statistics.pptx
Version 1 Analytics
 
Customise Your Correlation Table in IBM SPSS Statistics.pptx
Version 1 Analytics
 
Driver Easy Pro 6.1.1 Crack Licensce key 2025 FREE
utfefguu
 
4K Video Downloader Plus Pro Crack for MacOS New Download 2025
bashirkhan333g
 
OpenChain @ OSS NA - In From the Cold: Open Source as Part of Mainstream Soft...
Shane Coughlan
 
Download Canva Pro 2025 PC Crack Full Latest Version
bashirkhan333g
 
Automate Cybersecurity Tasks with Python
VICTOR MAESTRE RAMIREZ
 
Open Chain Q2 Steering Committee Meeting - 2025-06-25
Shane Coughlan
 
Change Common Properties in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
AOMEI Partition Assistant Crack 10.8.2 + WinPE Free Downlaod New Version 2025
bashirkhan333g
 
Comprehensive Risk Assessment Module for Smarter Risk Management
EHA Soft Solutions
 
Technical-Careers-Roadmap-in-Software-Market.pdf
Hussein Ali
 
Coefficient of Variance in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
Ad

Jpa 2.1 Application Development

  • 2. Why JPA ?  Java Persistence API (JPA), was introduced into the platform to bridge the gap between object-oriented domain models and relational database systems  API is part of javax.persistence.* package distributed by different vendors hibernate-jpa- 2.1-api.jar
  • 4. JPA Terminology  Entity: It is nothing but a java representation of the database table that should have characteristics like persist ability, identity, transactional and granularity.  Persistence Unit: Configuration of Entities and DB access information. (persistence.xml file)  EntityManagerFactory: Factory of Entity Managers which we can create by passing Persistence Unit.  EntityManager: Different API calls performed on entities are managed by the single interface called EntityManager.  PersistenceContext: Set of entities which are managed by the entity manager are called persistence context.  Persistence Provider: Provides underlying implementation to the APIs. (hibernate, eclipse link etc..)
  • 6. Characteristics of an Entity An entity class must follow these requirements.  The class must be annotated with the javax.persistence.Entity annotation.  The class must have a public or protected, no-argument constructor. The class may have other constructors.  The class must not be declared final. No methods or persistent instance variables must be declared final.  If an entity instance is passed by value as a detached object, such as through a session bean’s remote business interface, the class must implement the Serializable interface.  Entities may extend both entity and non-entity classes, and non-entity classes may extend entity classes.  Persistent instance variables must be declared private, protected, or package-private and can be accessed directly only by the entity class’s methods. Clients must access the entity’s state through accessor or business methods.
  • 7. Persistence UNIT and Context  A persistence unit is a named configuration of entity classes.  A persistence context is a managed set of entity instances.  Every persistence context is associated with a persistence unit, restricting the classes of the managed instances to the set defined by the persistence unit.  Saying that an entity instance is managed means that it is contained within a persistence context and it can be acted upon by an entity manager. It is for this reason that we say that an entity manager manages a persistence context.  The entity manager type determines the lifetime of a persistence context
  • 8. Entity Manager types  Container Managed Entity Managers: Lifecycle of the entity manager managed by the container. @PersistenceContext(unitName="MysqlPU") EntityManager entityManager;  Transaction-scoped: This means that the persistence contexts managed by the entity manager are scoped by the active JTA transaction, ending when the transaction is complete.  Extended: persistence context of an extended entity manager will last for the entire length of the conversation of service (ex: stateful session bean)  Application Managed Entity Manager : application will manages the lifecycle of the entity manager. final EntityManagerFactory emf = Persistence.createEntityManagerFactory("MysqlPU"); final EntityManager em = emf.createEntityManager();
  • 9. Transaction Managers  There are two types of transaction managers supported by the JPA  Resource Local : native transactions of the JDBC drivers that are referenced by a persistence unit.  JTA: transactions of the Java EE server, supporting multiple participating resources, transaction lifecycle management, and distributed XA transactions.  Container-managed entity managers always use JTA transactions, while application-managed entity managers can use either type.  Because JTA is typically not available in Java SE applications, the provider needs to support only resource- local transactions in that environment.  The default and preferred transaction type for Java EE applications is JTA. propagating persistence contexts with JTA transactions is a major benefit to enterprise persistence applications.
  • 10. Container Managed VS Application Managed EntityManager Container Managed EntityManager @PersistenceContext EntityManager em; Application Managed EntityManager @PersistenceUnit EntityManagerFactory emf; Ref: http://piotrnowicki.com/2012/11/types-of- entitymanagers-application-managed-entitymanager/
  • 11. Extended Vs Transactional Scoped  This feature tells us if the EntityManager’s operations might span across multiple transactions. By default the Transactional Persistence Context is used which means that all changes are flushed and all managed entities become detached when the current transaction commits.  The extended scope is available only for Stateful EJBs; it makes perfectly sense as the SFSBs can save the state, so end of one business method doesn’t necessary means the end of the transaction.  With the SLSB the story is different – we have business method that must end when the business method finishes because in next invocation we don’t have an idea which EJB instance we’ll end in. One method = one transaction; only transactional-scoped EntityManager is allowed for SLSB. NOTE: Extended and transaction scoped PersistenceContext are allowed only in case of container-managed EntityManagers.
  • 12. JPQL (Java Persistence query Language)  It is similar to SQL queries but it refers Entity names instead of table names. @Entity(name="Employee") @Table(name = "employee_tbl") public class EmployeeEntity { } JPQL: SELECT e FROM Employee e;
  • 13. QUERY PARAMETERS NOTATION  POSITIONAL PARAMETERS final Query positionalParamQuery = em.createQuery("SELECT e FROM Employee e WHERE e.id>?1", EmployeeEntity.class); positionalParamQuery.setParameter(1, 1600l);  NAMED PARAMETERS final Query namedParameterQuery = em.createQuery("SELECT e FROM Employee e WHERE e.id>=:id", EmployeeEntity.class); namedParameterQuery.setParameter("id", 1700l);
  • 14. Named Queries (Recommended) Persistence providers will often take steps to precompile JPQL named queries to SQL as part of the deployment or initialization phase of an application @Entity(name = "Employee") @Table(name = "employee_tbl") @NamedQuery(name = "employeeById", query = "SELECT e FROM Employee e WHERE e.id=:id") public class EmployeeEntity {} final Query namedQuery = em.createNamedQuery("employeeById"); namedQuery.setParameter("id", 1801l);
  • 15. Query Hints AND ADVANCED QUERY Query hints are the JPA extension point for query features. A hint is simply a string name and object value. Hints allow features to be added to JPA without introducing a new API.  namedQuery.setHint("javax.persistence.query.ti meout", 1);  query.setHint("org.hibernate.cacheable", Boolean.TRUE); Advanced Query: SELECT NEW com.innominds.dto.Employee(e.id,e.name,e.salary,e.join Date) FROM Employee e
  • 16. INHERITANCE AND POLYMORPHISM  SELECT p FROM Project p WHERE p.employees IS NOT EMPTY  SELECT p FROM Project p WHERE TYPE(p) = DesignProject OR TYPE(p) = QualityProject  INNER JOIN QUERY EXAMPLE SELECT pFROM Employee e JOIN e.phones p
  • 17. SUB QUERIES  SELECT e FROM Employee e WHERE e.salary = (SELECT MAX(emp.salary) FROM Employee emp)
  • 18. COLLECTION EXPRESSION  SELECT e FROM Employee e WHERE e.directs IS NOT EMPTY  SELECT m FROM Employee m WHERE (SELECT COUNT(e) FROM Employee e WHERE e.manager = m) > 0
  • 19. MEMBER OF  The MEMBER OF operator and its negated form NOT MEMBER OF are a shorthand way of checking whether an entity is a member of a collection association path. SELECT e FROM Employee e WHERE e MEMBER OF e.directs
  • 20. Enabling SECOND LEVEL CACHE IN 4.0 (3.3.x) or higher  Hibernate has its own EHCache implementation from version 4 onwards. Add below properties to configuration <property name="hibernate.cache.region.factory_class" value="org.hibernate.cache.ehcache.EhCacheRegionFa ctory"/> <property name="hibernate.cache.use_second_level_cache" value="true" /> <property name="hibernate.cache.use_query_cache" value="true" /> <property name="hibernate.generate_statistics" value="true" />
  • 21. Second LEVEL CACHE MODES Second level cache can be controller using property "javax.persistence.sharedCache.mode". Following values are allowed  ALL: All entity data is stored in the 2nd level cache  NONE: No data is cached  ENABLE_SELECTIVE: Entities marked with @Cachable are cached  DISABLE_SELECTIVE: All entities except @Cachable(false) are cached  UNSPECIFIED: Caching behavior is not specified, Persistence provider’s default caching behavior is used. final Properties additionalConfig = new Properties(); additionalConfig.put("javax.persistence.sharedCache.mode", "DISABLE_SELECTIVE");
  • 22. Cache Retrieval and Store Modes  When the second level cache is enabled for a persistence unit, we’re now able fine-tune the caching behavior by setting retrieval-mode and store-mode-properties at persistence context level or for each entity-manager operation or query level by setting below properties.  Retrieve Mode can be set using below property javax.persistence.cache.retrieveMode  Store Mode can be set using below property javax.persistence.cache.storeMode
  • 23. Retrieve MODES  Following options are available for Retrieve mode  BYPASS: The cache is bypassed and a call to the database is used to retrieve the data.  USE: If the data is available in the cache, it is read from this location, else it is fetched from the database. EX: config.put("javax.persistence.cache.retrieveMode", CacheRetrieveMode.USE);
  • 24. CACHE STORE MODES  Following options are available for store mode  BYPASS: Don’t put anything into the cache  REFRESH: Data is put/updated in the cache when read and committed into the database a refresh enforced  USE: Data is put/updated in the cache when read and committed into the database
  • 25. Container Managed EntityManager  To demonstrate this scenario I used spring container to create EntityManagerFactory which reads the configuration from persistence.xml file. @Bean(name = "entityManagerFactory") public EntityManagerFactory entityManagerFactory() { final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); em.afterPropertiesSet();// IMP return em.getObject(); } NOTE: full java configuration without using persistence.xml also possible please refer the github source code link in the next slide.
  • 26.  Write a Dao class and annotate EntityManager as shown below @Repository("personDao") @Transactional(propagation = Propagation.REQUIRED) public class PersonDao { @PersistenceContext private EntityManager entityManager; … write your business methods here } NOTE: Working code available below location: https://github.com/Innominds-jee/jpa-cm-training.git
  • 27. Distributed Transactions using JTA  https://www.javacodegeeks.com/2013/07/spring- jta-multiple-resource-transactions-in-tomcat-with- atomikos-example.html  https://www.atomikos.com/Documentation/Hiberna teThreeStandalone  http://www.careerride.com/JTS-advantages-of- JTA-over-JTS.aspx  https://spring.io/blog/2011/08/15/configuring- spring-and-jta-without-full-java-ee/  http://www.javaworld.com/article/2077714/java- web-development/xa-transactions-using- spring.html  http://www.byteslounge.com/tutorials/spring- jta-multiple-resource-transactions-in-tomcat- with-atomikos-example