SlideShare a Scribd company logo
1 of 32
Java Persistence
API
AAAAAA
1. Introduction
Entities
Entity Relationship
Cascade Operation
Inheritance
Managing Entities
Entity LifeCycle Management
API Operations on Entity
Persistence Unit
Spring Configuration
Querying Entities
Difference Between JPA and Hibernate
Resources
Agenda
Introduction
• The Java Persistence API provides Java developers
with an object/relational mapping facility for
managing relational data in Java applications.
• JPA itself is just a specification, not a product, it
cannot perform persistence or anything else by
itself.
• JPA is just a set of interfaces, and requires an
implementation. There are open-source and
commercial JPA implementations to choose from
and any Java EE 5 application server should
provide support for its use.
• JPA also requires a database to persist to.
IM
Java Persistence
The Java Persistence consists of four areas:
• The Java Persistence API
• The Query Language
• The Java Persistence Criteria API
• Object/Relational Mapping Metadata
Entities
• An entity represents a table in a
relational database, and each
entity instance corresponds to a
row in that table.
• An entity is a lightweight
persistence domain object.
• The primary programming
artifact of an entity is the entity
class
IM
Requirements For Entity Classes
• The class must be annoyed with java.persistence.Entity
annotation .
• The class must not be declared final.
• The class must implement the Serializable interface.
• Entities may extend both entity and non-entity classes, and non-
entity classes may extend entity class.
• Persistent instance variable must be declared private, protected,
or package-private.
For Example: @Entity
class Employee{
….
}
and
Properties
The following Collections are used:
• java.util.Collection
• java.util.Set
• java.util.List
• java.util.Map
Entity Field and Properties[Conti..]
Properties [Conti..]
If a Field or Property of an entity consists of a
collection of basic types or embeddable classes
use the java.persistence.ElementCollection
annotation on the field or property
The 2 attributes of @ElementCollections are:
• fetch
• targetClass
Entity Field and Properties[Conti..]
The fetch attribute is used to specify whether the collection should be retrieved
lazily or eagerly, using java.persistence.FetchType contacts of LAZY or
EAGER, respectively. By default, the collection will be fetched LAZY.
The following entity, Employee, has a persistent field, first name, which is
collection of String classes that will be fetched eagerly. The targetClass
element is not required, because it uses generics to define the field.
@Entity
public class Employee{
….
@ElementCollection(fetch=EAGER)
protected Set<String> first name = new HashSet();
….
}
Primary Keys in Entities
Each entity has a unique object identifier.
A Primary key class have the following requirements:
• The access control modifier of the class must be public.
• The properties of the primary key class must be public or protected if property-based access
is used.
• The class must have a public default constructor and must be serializable.
• The class must implement the hashCode() and equals(Object other) methods.
@Entity
public class Employee {
@Id @Generated Value
private int id; Primary Key
private String first name;
….
public int getId() { return id; }
public void setId(int id) { this.id = id; }
….
}
M
There are four types of relationship
multiplicities:
• @OneToOne
• @OneToMany
• @ManyToOne
• @ManyToMany
The direction of the relationship can
be:
• bidirectional
• unidirectional
IM
OneToOne Mapping
Each entity instance is related to a single instance of another
entity
For Example: @Entity
public class Employee {
@Id
@Column(name=“EMP_id”)
private long id;
….
@OneToOne(fetch=FetchType.LAZY)
@JoinColumn(name=“ADDRESS_ID”)
private Address address;
.…
}
OneToMany Mapping
An entity instance can be related to a multiple instance of
other entities.
For Example: @Entity
public class Employee {
@Id
@Column(name=“EMP_id”)
private long id;
….
@OneToMany(mappedBy="owner")
private List<Phone> phones;
.…
}
ManyToOne Mapping
Multiple instances of an entity can be related to a single
instance of the other entity. This multiplicity is the opposite of
a one-to-many relationship.
For Example: @Entity
public class Phone{
@Id
private long id;
….
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="OWNER_ID”)
private Employee owner;
.…
}
ManyToMany Mapping
The entity instance can be related to multiple instances of each
other
Instruction:
• If “One" end of the relationship is owning side, then foreign key
column is generated for the entity in database
• If “Many” end of the relationship is the owning side, then join table is
generated.
Cascade Operation
The java.persistence.CascadeType
enumerated type defines the
cascade operation that are applied
in the cascade element of the
relationship annotations
IM
Cascade Operations [Conti..]
Cascade
Operation Description
ALL
All cascade operations will be applied to the parent entities related entity. All is equivalent to
specifying cascade={DETACH, MERGE,PERSIST, REFRESH, REMOVE}
DETACH
If the parent entity is detached from the persistence context, the related entity will also be
detached
MERGE
If the parent entity is merged into the persistence context, the related entity will also be
merged
PERSIST
if the parent entity is persisted into the persistence context, the related entity will also be
persisted
REFRESH
if the parent entity is refreshed in the current persistence context, the related entity will be
refreshed
REMOVE
if the parent entity is removed from the current persistence context, the related entity will
also be removed
Cascade Operations [Conti..]
For Example:
A line item is part of an order, if the order is deleted, the line item
also should be deleted using the cascade = REMOVE element
specification for @OneToOne and @OneToMany relationships. This
is called a cascade delete relationship.
@OneToMany(cascade = REMOVE, mappedBy = “employee”)
public Set<Name> getNames() { return names; }
Inheritance
• 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:
1. SINGLE_TABLE
2. JOINED
3. TABLE_PER_CLASS
IM
Managing Entities
• Entities are managed by the entity
manager, which is represented by
java.persistence.EntityManager
instance.
• Each EntityManager instance is
associated with a persistence
context, which defines particular
entity instance are created,
persisted and removed.
IM
Managing Entities [Conti..]
To Obtain Entity Manager instance, you must first obtain an EntityManagerFactory instance by
injecting it into the application component by means of the java.persistence.PersistenceUnit
annotation.
The Example illustrates how to manage transactions in an application that uses an Application-
Managed Entity Manager:
@PersitenceContext
EntityManagerFactory emf;
EntityManager em;
@Resource,
UserTransaction utx;
...
em = emf.createEntityManager();
try {
utx.begin();
em.persist(SomeEntity);
em.merge(AnotherEntity);
em.remove(ThirdEntity);
utx.commit();
} catch (Exception e) {
utx.rollback();
Entity LifeCycle
Management
IM
API Operations on Entity
List of EntityManager API operations:
persist()- Insert the state of an entity into db
remove()- Delete the entity state from the db
refresh()- Reload the entity state from the db
merge()- Synchronize the state of detached entity with
the pc
find()- Execute a simple PK query
createQuery()- Create query instance using dynamic
JP QL
createNamedQuery()- Create instance for a
predefined query
createNativeQuery()- Create instance for an SQL
query
contains()- Determine if entity is managed by pc
flush()- Force synchronization of pc to database
IM
Persistence Unit
A persistence unit defines a set
of all entity classes that are
managed by EntityManager
instances in an application. This
set of entity classes represents
the data contained within a
single data store.
IM
Persistence Unit [Conti..]
Persistence units are defined by the resource/META-
INF/persistence.xml configuration file.
The following is an example persistence.xml file:
<persistence>
<persistence-unit name="EmployeeManagement">
<description>This unit manages employee and company.
It does not rely on any vendor-specific features and can
therefore be deployed to any persistence provider.
</description>
<jta-data-source>jdbc/EmployeeDB</jta-data-source>
<jar-file>EmployeeApp.jar</jar-file>
<class>com.Employee</class>
<class>com.Company</class>
</persistence-unit>
</persistence>
Hibernate Persistence [Conti..]
For Example:
<persistence-unit name="demoPU" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="hibernate.dialect"
value="org.hibernate.dialect.PostgreSQLDialect"/>
<property name=“javax.persistence.jdbc.driver"
value="org.postgresql.Driver" />
<property name="javax.persistence.jdbc.url"
value=“jdbc:postgresql://localhost:5432/ demo" />
<property name="javax.persistence.jdbc.user" value="postgres"/>
<property name="javax.persistence.jdbc.password" value=“***”/>
<property name="hibernate.hbm2ddl.auto" value="create" />
</properties>
</persistence-unit>
Hibernate.hbm2ddl.auto
This hibernate,hbm2ddl.auto is used to validate or export DDL
schema to the database when the SessionFactory is created.
Possible Values are:
• validate
• create
• update
• create-drop
Spring
Configuration
EntityManager injection:
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="persistenceUnitName" value="demoPU" />
<property name="jpaVendorAdapter">
<bean
class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="generateDdl" value="true" />
<property name="showSql" value="true" />
<property name="databasePlatform"
value="org.hibernate.dialect.PostgreSQLDialect" />
</bean>
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">create</prop>
</props>
</property>
</bean>
IM
Spring Configuration
Transaction Manager injection:
<bean id="transactionManager“
class=“org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
Querying Entities
The Java Persistence API provides the
following methods for querying
entities:
• The Criteria API is used to create type safe queries using
Java Programming language API’s to query for entities
and their relationships.
• The Java Persistence query language (JPQL) is a simple,
string-based language similar to SQL used to query entities
and their relationships.
IM
Difference Between JPA and
Hibernate
JPA is just guidelines to implement the Object Relational Mapping (ORM) and
there is no underlying code for the implementation.Where as, Hibernate is the
actual implementation of JPA guidelines. When hibernate implements the JPA
specification.
Hibernate is a JPA provider. When there is new changes to the specification,
hibernate would release its updated implementation for the JPA specification.
In summary, JPA is not an implementation, it will not provide any concrete
functionality to your application. Its purpose is to provide a set of rules and
guidelines that can be followed by JPA implementation vendors to create an ORM
implementation in a standardized manner. Hibernate is the most popular JPA
provider.
Resources
• Oracle: Java Persistence API:-
http://www.oracle.com/technetwork/java/javaee/tech/persistence
-jsp-140049.html
• The Java Persistence API - A Simpler
Programming Model for Entity Persistence:-
http://www.oracle.com/technetwork/articles/javaee/jpa-
137156.html
• JPA Annotation Reference:-
http://www.oracle.com/technetwork/middleware/ias/toplink-jpa-
annotations-096251.html
• Hibernate Reference Documentation:-
http://docs.jboss.org/hibernate/orm/4.2/manual/en-US/html/

More Related Content

What's hot

What's hot (20)

Hibernate in Action
Hibernate in ActionHibernate in Action
Hibernate in Action
 
Spring beans
Spring beansSpring beans
Spring beans
 
Hibernate architecture
Hibernate architectureHibernate architecture
Hibernate architecture
 
Spring & hibernate
Spring & hibernateSpring & hibernate
Spring & hibernate
 
Spring data jpa
Spring data jpaSpring data jpa
Spring data jpa
 
Spring boot
Spring bootSpring boot
Spring boot
 
Spring Data JPA
Spring Data JPASpring Data JPA
Spring Data JPA
 
Hibernate ppt
Hibernate pptHibernate ppt
Hibernate ppt
 
Introduction to Spring Boot
Introduction to Spring BootIntroduction to Spring Boot
Introduction to Spring Boot
 
Introduction to JPA and Hibernate including examples
Introduction to JPA and Hibernate including examplesIntroduction to JPA and Hibernate including examples
Introduction to JPA and Hibernate including examples
 
Spring boot Introduction
Spring boot IntroductionSpring boot Introduction
Spring boot Introduction
 
Spring boot
Spring bootSpring boot
Spring boot
 
Spring boot introduction
Spring boot introductionSpring boot introduction
Spring boot introduction
 
Introduction to spring boot
Introduction to spring bootIntroduction to spring boot
Introduction to spring boot
 
Spring Framework
Spring Framework  Spring Framework
Spring Framework
 
Session bean
Session beanSession bean
Session bean
 
REST APIs with Spring
REST APIs with SpringREST APIs with Spring
REST APIs with Spring
 
Spring jdbc
Spring jdbcSpring jdbc
Spring jdbc
 
Spring Core
Spring CoreSpring Core
Spring Core
 
Java EE Introduction
Java EE IntroductionJava EE Introduction
Java EE Introduction
 

Viewers also liked

Spring + JPA + DAO Step by Step
Spring + JPA + DAO Step by StepSpring + JPA + DAO Step by Step
Spring + JPA + DAO Step by Step
Guo Albert
 

Viewers also liked (20)

Spring.Boot up your development
Spring.Boot up your developmentSpring.Boot up your development
Spring.Boot up your development
 
Spring
SpringSpring
Spring
 
Java persistence api
Java persistence api Java persistence api
Java persistence api
 
Gradle - Build System
Gradle - Build SystemGradle - Build System
Gradle - Build System
 
Spring Data Jpa
Spring Data JpaSpring Data Jpa
Spring Data Jpa
 
Thinking Beyond ORM in JPA
Thinking Beyond ORM in JPAThinking Beyond ORM in JPA
Thinking Beyond ORM in JPA
 
Hibernate using jpa
Hibernate using jpaHibernate using jpa
Hibernate using jpa
 
Lazy vs. Eager Loading Strategies in JPA 2.1
Lazy vs. Eager Loading Strategies in JPA 2.1Lazy vs. Eager Loading Strategies in JPA 2.1
Lazy vs. Eager Loading Strategies in JPA 2.1
 
Colloquium Report
Colloquium ReportColloquium Report
Colloquium Report
 
Secure Authentication and Session Management in Java EE
Secure Authentication and Session Management in Java EESecure Authentication and Session Management in Java EE
Secure Authentication and Session Management in Java EE
 
Spring Boot. Boot up your development
Spring Boot. Boot up your developmentSpring Boot. Boot up your development
Spring Boot. Boot up your development
 
Second Level Cache in JPA Explained
Second Level Cache in JPA ExplainedSecond Level Cache in JPA Explained
Second Level Cache in JPA Explained
 
JPA - Beyond copy-paste
JPA - Beyond copy-pasteJPA - Beyond copy-paste
JPA - Beyond copy-paste
 
JDBC - JPA - Spring Data
JDBC - JPA - Spring DataJDBC - JPA - Spring Data
JDBC - JPA - Spring Data
 
Spring Data Jpa
Spring Data JpaSpring Data Jpa
Spring Data Jpa
 
Amazon Webservices for Java Developers - UCI Webinar
Amazon Webservices for Java Developers - UCI WebinarAmazon Webservices for Java Developers - UCI Webinar
Amazon Webservices for Java Developers - UCI Webinar
 
Junior,middle,senior?
Junior,middle,senior?Junior,middle,senior?
Junior,middle,senior?
 
Introduction to JPA Framework
Introduction to JPA FrameworkIntroduction to JPA Framework
Introduction to JPA Framework
 
Spring + JPA + DAO Step by Step
Spring + JPA + DAO Step by StepSpring + JPA + DAO Step by Step
Spring + JPA + DAO Step by Step
 
Java Persistence API (JPA) - A Brief Overview
Java Persistence API (JPA) - A Brief OverviewJava Persistence API (JPA) - A Brief Overview
Java Persistence API (JPA) - A Brief Overview
 

Similar to JPA For Beginner's

Hibernate Training Session1
Hibernate Training Session1Hibernate Training Session1
Hibernate Training Session1
Asad Khan
 
Advanced Hibernate V2
Advanced Hibernate V2Advanced Hibernate V2
Advanced Hibernate V2
Haitham Raik
 
Entity Manager
Entity ManagerEntity Manager
Entity Manager
patinijava
 

Similar to JPA For Beginner's (20)

Jpa 2.1 Application Development
Jpa 2.1 Application DevelopmentJpa 2.1 Application Development
Jpa 2.1 Application Development
 
Introduction to JPA (JPA version 2.0)
Introduction to JPA (JPA version 2.0)Introduction to JPA (JPA version 2.0)
Introduction to JPA (JPA version 2.0)
 
Ecom lec4 fall16_jpa
Ecom lec4 fall16_jpaEcom lec4 fall16_jpa
Ecom lec4 fall16_jpa
 
Jpa
JpaJpa
Jpa
 
Ejb3 Presentation
Ejb3 PresentationEjb3 Presentation
Ejb3 Presentation
 
Introduction to Datastore
Introduction to DatastoreIntroduction to Datastore
Introduction to Datastore
 
JavaEE Spring Seam
JavaEE Spring SeamJavaEE Spring Seam
JavaEE Spring Seam
 
Doctrine ORM Internals. UnitOfWork
Doctrine ORM Internals. UnitOfWorkDoctrine ORM Internals. UnitOfWork
Doctrine ORM Internals. UnitOfWork
 
Entity Persistence with JPA
Entity Persistence with JPAEntity Persistence with JPA
Entity Persistence with JPA
 
Configuring jpa in a Spring application
Configuring jpa in a  Spring applicationConfiguring jpa in a  Spring application
Configuring jpa in a Spring application
 
Hibernate
HibernateHibernate
Hibernate
 
Hibernate
HibernateHibernate
Hibernate
 
Hibernate
HibernateHibernate
Hibernate
 
java framwork for HIBERNATE FRAMEWORK.pptx
java framwork for HIBERNATE FRAMEWORK.pptxjava framwork for HIBERNATE FRAMEWORK.pptx
java framwork for HIBERNATE FRAMEWORK.pptx
 
React JS; all concepts. Contains React Features, JSX, functional & Class comp...
React JS; all concepts. Contains React Features, JSX, functional & Class comp...React JS; all concepts. Contains React Features, JSX, functional & Class comp...
React JS; all concepts. Contains React Features, JSX, functional & Class comp...
 
Hibernate Training Session1
Hibernate Training Session1Hibernate Training Session1
Hibernate Training Session1
 
Java Web Programming on Google Cloud Platform [2/3] : Datastore
Java Web Programming on Google Cloud Platform [2/3] : DatastoreJava Web Programming on Google Cloud Platform [2/3] : Datastore
Java Web Programming on Google Cloud Platform [2/3] : Datastore
 
Advanced Hibernate V2
Advanced Hibernate V2Advanced Hibernate V2
Advanced Hibernate V2
 
Entity Manager
Entity ManagerEntity Manager
Entity Manager
 
Ejb6
Ejb6Ejb6
Ejb6
 

Recently uploaded

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 

Recently uploaded (20)

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Cyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfCyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdf
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 

JPA For Beginner's

  • 2. AAAAAA 1. Introduction Entities Entity Relationship Cascade Operation Inheritance Managing Entities Entity LifeCycle Management API Operations on Entity Persistence Unit Spring Configuration Querying Entities Difference Between JPA and Hibernate Resources Agenda
  • 3. Introduction • The Java Persistence API provides Java developers with an object/relational mapping facility for managing relational data in Java applications. • JPA itself is just a specification, not a product, it cannot perform persistence or anything else by itself. • JPA is just a set of interfaces, and requires an implementation. There are open-source and commercial JPA implementations to choose from and any Java EE 5 application server should provide support for its use. • JPA also requires a database to persist to. IM
  • 4. Java Persistence The Java Persistence consists of four areas: • The Java Persistence API • The Query Language • The Java Persistence Criteria API • Object/Relational Mapping Metadata
  • 5. Entities • An entity represents a table in a relational database, and each entity instance corresponds to a row in that table. • An entity is a lightweight persistence domain object. • The primary programming artifact of an entity is the entity class IM
  • 6. Requirements For Entity Classes • The class must be annoyed with java.persistence.Entity annotation . • The class must not be declared final. • The class must implement the Serializable interface. • Entities may extend both entity and non-entity classes, and non- entity classes may extend entity class. • Persistent instance variable must be declared private, protected, or package-private. For Example: @Entity class Employee{ …. }
  • 7. and Properties The following Collections are used: • java.util.Collection • java.util.Set • java.util.List • java.util.Map
  • 8. Entity Field and Properties[Conti..] Properties [Conti..] If a Field or Property of an entity consists of a collection of basic types or embeddable classes use the java.persistence.ElementCollection annotation on the field or property The 2 attributes of @ElementCollections are: • fetch • targetClass
  • 9. Entity Field and Properties[Conti..] The fetch attribute is used to specify whether the collection should be retrieved lazily or eagerly, using java.persistence.FetchType contacts of LAZY or EAGER, respectively. By default, the collection will be fetched LAZY. The following entity, Employee, has a persistent field, first name, which is collection of String classes that will be fetched eagerly. The targetClass element is not required, because it uses generics to define the field. @Entity public class Employee{ …. @ElementCollection(fetch=EAGER) protected Set<String> first name = new HashSet(); …. }
  • 10. Primary Keys in Entities Each entity has a unique object identifier. A Primary key class have the following requirements: • The access control modifier of the class must be public. • The properties of the primary key class must be public or protected if property-based access is used. • The class must have a public default constructor and must be serializable. • The class must implement the hashCode() and equals(Object other) methods. @Entity public class Employee { @Id @Generated Value private int id; Primary Key private String first name; …. public int getId() { return id; } public void setId(int id) { this.id = id; } …. }
  • 11. M There are four types of relationship multiplicities: • @OneToOne • @OneToMany • @ManyToOne • @ManyToMany The direction of the relationship can be: • bidirectional • unidirectional IM
  • 12. OneToOne Mapping Each entity instance is related to a single instance of another entity For Example: @Entity public class Employee { @Id @Column(name=“EMP_id”) private long id; …. @OneToOne(fetch=FetchType.LAZY) @JoinColumn(name=“ADDRESS_ID”) private Address address; .… }
  • 13. OneToMany Mapping An entity instance can be related to a multiple instance of other entities. For Example: @Entity public class Employee { @Id @Column(name=“EMP_id”) private long id; …. @OneToMany(mappedBy="owner") private List<Phone> phones; .… }
  • 14. ManyToOne Mapping Multiple instances of an entity can be related to a single instance of the other entity. This multiplicity is the opposite of a one-to-many relationship. For Example: @Entity public class Phone{ @Id private long id; …. @ManyToOne(fetch=FetchType.LAZY) @JoinColumn(name="OWNER_ID”) private Employee owner; .… }
  • 15. ManyToMany Mapping The entity instance can be related to multiple instances of each other Instruction: • If “One" end of the relationship is owning side, then foreign key column is generated for the entity in database • If “Many” end of the relationship is the owning side, then join table is generated.
  • 16. Cascade Operation The java.persistence.CascadeType enumerated type defines the cascade operation that are applied in the cascade element of the relationship annotations IM
  • 17. Cascade Operations [Conti..] Cascade Operation Description ALL All cascade operations will be applied to the parent entities related entity. All is equivalent to specifying cascade={DETACH, MERGE,PERSIST, REFRESH, REMOVE} DETACH If the parent entity is detached from the persistence context, the related entity will also be detached MERGE If the parent entity is merged into the persistence context, the related entity will also be merged PERSIST if the parent entity is persisted into the persistence context, the related entity will also be persisted REFRESH if the parent entity is refreshed in the current persistence context, the related entity will be refreshed REMOVE if the parent entity is removed from the current persistence context, the related entity will also be removed
  • 18. Cascade Operations [Conti..] For Example: A line item is part of an order, if the order is deleted, the line item also should be deleted using the cascade = REMOVE element specification for @OneToOne and @OneToMany relationships. This is called a cascade delete relationship. @OneToMany(cascade = REMOVE, mappedBy = “employee”) public Set<Name> getNames() { return names; }
  • 19. Inheritance • 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: 1. SINGLE_TABLE 2. JOINED 3. TABLE_PER_CLASS IM
  • 20. Managing Entities • Entities are managed by the entity manager, which is represented by java.persistence.EntityManager instance. • Each EntityManager instance is associated with a persistence context, which defines particular entity instance are created, persisted and removed. IM
  • 21. Managing Entities [Conti..] To Obtain Entity Manager instance, you must first obtain an EntityManagerFactory instance by injecting it into the application component by means of the java.persistence.PersistenceUnit annotation. The Example illustrates how to manage transactions in an application that uses an Application- Managed Entity Manager: @PersitenceContext EntityManagerFactory emf; EntityManager em; @Resource, UserTransaction utx; ... em = emf.createEntityManager(); try { utx.begin(); em.persist(SomeEntity); em.merge(AnotherEntity); em.remove(ThirdEntity); utx.commit(); } catch (Exception e) { utx.rollback();
  • 23. API Operations on Entity List of EntityManager API operations: persist()- Insert the state of an entity into db remove()- Delete the entity state from the db refresh()- Reload the entity state from the db merge()- Synchronize the state of detached entity with the pc find()- Execute a simple PK query createQuery()- Create query instance using dynamic JP QL createNamedQuery()- Create instance for a predefined query createNativeQuery()- Create instance for an SQL query contains()- Determine if entity is managed by pc flush()- Force synchronization of pc to database IM
  • 24. Persistence Unit A persistence unit defines a set of all entity classes that are managed by EntityManager instances in an application. This set of entity classes represents the data contained within a single data store. IM
  • 25. Persistence Unit [Conti..] Persistence units are defined by the resource/META- INF/persistence.xml configuration file. The following is an example persistence.xml file: <persistence> <persistence-unit name="EmployeeManagement"> <description>This unit manages employee and company. It does not rely on any vendor-specific features and can therefore be deployed to any persistence provider. </description> <jta-data-source>jdbc/EmployeeDB</jta-data-source> <jar-file>EmployeeApp.jar</jar-file> <class>com.Employee</class> <class>com.Company</class> </persistence-unit> </persistence>
  • 26. Hibernate Persistence [Conti..] For Example: <persistence-unit name="demoPU" transaction-type="RESOURCE_LOCAL"> <provider>org.hibernate.ejb.HibernatePersistence</provider> <properties> <property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect"/> <property name=“javax.persistence.jdbc.driver" value="org.postgresql.Driver" /> <property name="javax.persistence.jdbc.url" value=“jdbc:postgresql://localhost:5432/ demo" /> <property name="javax.persistence.jdbc.user" value="postgres"/> <property name="javax.persistence.jdbc.password" value=“***”/> <property name="hibernate.hbm2ddl.auto" value="create" /> </properties> </persistence-unit>
  • 27. Hibernate.hbm2ddl.auto This hibernate,hbm2ddl.auto is used to validate or export DDL schema to the database when the SessionFactory is created. Possible Values are: • validate • create • update • create-drop
  • 28. Spring Configuration EntityManager injection: <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="persistenceUnitName" value="demoPU" /> <property name="jpaVendorAdapter"> <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"> <property name="generateDdl" value="true" /> <property name="showSql" value="true" /> <property name="databasePlatform" value="org.hibernate.dialect.PostgreSQLDialect" /> </bean> </property> <property name="jpaProperties"> <props> <prop key="hibernate.hbm2ddl.auto">create</prop> </props> </property> </bean> IM
  • 29. Spring Configuration Transaction Manager injection: <bean id="transactionManager“ class=“org.springframework.orm.jpa.JpaTransactionManager"> <property name="entityManagerFactory" ref="entityManagerFactory"/> </bean> <tx:annotation-driven transaction-manager="transactionManager"/>
  • 30. Querying Entities The Java Persistence API provides the following methods for querying entities: • The Criteria API is used to create type safe queries using Java Programming language API’s to query for entities and their relationships. • The Java Persistence query language (JPQL) is a simple, string-based language similar to SQL used to query entities and their relationships. IM
  • 31. Difference Between JPA and Hibernate JPA is just guidelines to implement the Object Relational Mapping (ORM) and there is no underlying code for the implementation.Where as, Hibernate is the actual implementation of JPA guidelines. When hibernate implements the JPA specification. Hibernate is a JPA provider. When there is new changes to the specification, hibernate would release its updated implementation for the JPA specification. In summary, JPA is not an implementation, it will not provide any concrete functionality to your application. Its purpose is to provide a set of rules and guidelines that can be followed by JPA implementation vendors to create an ORM implementation in a standardized manner. Hibernate is the most popular JPA provider.
  • 32. Resources • Oracle: Java Persistence API:- http://www.oracle.com/technetwork/java/javaee/tech/persistence -jsp-140049.html • The Java Persistence API - A Simpler Programming Model for Entity Persistence:- http://www.oracle.com/technetwork/articles/javaee/jpa- 137156.html • JPA Annotation Reference:- http://www.oracle.com/technetwork/middleware/ias/toplink-jpa- annotations-096251.html • Hibernate Reference Documentation:- http://docs.jboss.org/hibernate/orm/4.2/manual/en-US/html/