SlideShare a Scribd company logo
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

PPSX
Spring - Part 1 - IoC, Di and Beans
Hitesh-Java
 
PDF
JPA and Hibernate
elliando dias
 
PPT
jpa-hibernate-presentation
John Slick
 
PPT
Java Persistence API (JPA) Step By Step
Guo Albert
 
PDF
Spring MVC Framework
Hùng Nguyễn Huy
 
PDF
Hibernate Presentation
guest11106b
 
PDF
Java persistence api 2.1
Rakesh K. Cherukuri
 
PPTX
Introduction to Spring Boot
Purbarun Chakrabarti
 
Spring - Part 1 - IoC, Di and Beans
Hitesh-Java
 
JPA and Hibernate
elliando dias
 
jpa-hibernate-presentation
John Slick
 
Java Persistence API (JPA) Step By Step
Guo Albert
 
Spring MVC Framework
Hùng Nguyễn Huy
 
Hibernate Presentation
guest11106b
 
Java persistence api 2.1
Rakesh K. Cherukuri
 
Introduction to Spring Boot
Purbarun Chakrabarti
 

What's hot (20)

PPT
PHP - Introduction to Object Oriented Programming with PHP
Vibrant Technologies & Computers
 
PPTX
Hibernate ppt
Aneega
 
PPT
Java J2EE
Sandeep Rawat
 
PPT
Java collection
Arati Gadgil
 
PPTX
Spring Boot
Jiayun Zhou
 
PDF
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
Edureka!
 
PPTX
Spring data jpa
Jeevesh Pandey
 
PPTX
Spring boot Introduction
Jeevesh Pandey
 
PDF
Spring Framework - AOP
Dzmitry Naskou
 
PDF
Spring Framework
NexThoughts Technologies
 
PDF
Spring MVC
Aaron Schram
 
PPTX
Spring Boot Tutorial
Naphachara Rattanawilai
 
PDF
Java8 features
Elias Hasnat
 
PPT
Jpa
Manav Prasad
 
PDF
Spring Boot
Jaydeep Kale
 
PDF
Spring Data JPA from 0-100 in 60 minutes
VMware Tanzu
 
PDF
Java Collection framework
ankitgarg_er
 
PPTX
java Servlet technology
Tanmoy Barman
 
PPS
Java Hibernate Programming with Architecture Diagram and Example
kamal kotecha
 
PDF
Spring Framework - Core
Dzmitry Naskou
 
PHP - Introduction to Object Oriented Programming with PHP
Vibrant Technologies & Computers
 
Hibernate ppt
Aneega
 
Java J2EE
Sandeep Rawat
 
Java collection
Arati Gadgil
 
Spring Boot
Jiayun Zhou
 
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
Edureka!
 
Spring data jpa
Jeevesh Pandey
 
Spring boot Introduction
Jeevesh Pandey
 
Spring Framework - AOP
Dzmitry Naskou
 
Spring Framework
NexThoughts Technologies
 
Spring MVC
Aaron Schram
 
Spring Boot Tutorial
Naphachara Rattanawilai
 
Java8 features
Elias Hasnat
 
Spring Boot
Jaydeep Kale
 
Spring Data JPA from 0-100 in 60 minutes
VMware Tanzu
 
Java Collection framework
ankitgarg_er
 
java Servlet technology
Tanmoy Barman
 
Java Hibernate Programming with Architecture Diagram and Example
kamal kotecha
 
Spring Framework - Core
Dzmitry Naskou
 
Ad

Viewers also liked (20)

PPTX
Spring.Boot up your development
Strannik_2013
 
PPT
Java persistence api
Luis Goldster
 
PDF
Gradle - Build System
Jeevesh Pandey
 
PDF
Spring Data Jpa
Ivan Queiroz
 
PPTX
Thinking Beyond ORM in JPA
Patrycja Wegrzynowicz
 
PDF
Hibernate using jpa
Mohammad Faizan
 
PDF
Lazy vs. Eager Loading Strategies in JPA 2.1
Patrycja Wegrzynowicz
 
DOCX
Colloquium Report
Mohammad Faizan
 
PDF
Secure Authentication and Session Management in Java EE
Patrycja Wegrzynowicz
 
PPT
Spring Boot. Boot up your development
Strannik_2013
 
PDF
Second Level Cache in JPA Explained
Patrycja Wegrzynowicz
 
PDF
JPA - Beyond copy-paste
Jakub Kubrynski
 
PPTX
JDBC - JPA - Spring Data
Arturs Drozdovs
 
PDF
Spring Data Jpa
Ivan Queiroz
 
PPTX
Amazon Webservices for Java Developers - UCI Webinar
Craig Dickson
 
PPTX
Junior,middle,senior?
Strannik_2013
 
PPTX
Introduction to JPA Framework
Collaboration Technologies
 
PPT
Spring + JPA + DAO Step by Step
Guo Albert
 
PPT
Java Persistence API (JPA) - A Brief Overview
Craig Dickson
 
Spring.Boot up your development
Strannik_2013
 
Java persistence api
Luis Goldster
 
Gradle - Build System
Jeevesh Pandey
 
Spring Data Jpa
Ivan Queiroz
 
Thinking Beyond ORM in JPA
Patrycja Wegrzynowicz
 
Hibernate using jpa
Mohammad Faizan
 
Lazy vs. Eager Loading Strategies in JPA 2.1
Patrycja Wegrzynowicz
 
Colloquium Report
Mohammad Faizan
 
Secure Authentication and Session Management in Java EE
Patrycja Wegrzynowicz
 
Spring Boot. Boot up your development
Strannik_2013
 
Second Level Cache in JPA Explained
Patrycja Wegrzynowicz
 
JPA - Beyond copy-paste
Jakub Kubrynski
 
JDBC - JPA - Spring Data
Arturs Drozdovs
 
Spring Data Jpa
Ivan Queiroz
 
Amazon Webservices for Java Developers - UCI Webinar
Craig Dickson
 
Junior,middle,senior?
Strannik_2013
 
Introduction to JPA Framework
Collaboration Technologies
 
Spring + JPA + DAO Step by Step
Guo Albert
 
Java Persistence API (JPA) - A Brief Overview
Craig Dickson
 
Ad

Similar to JPA For Beginner's (20)

PPTX
Jpa 2.1 Application Development
ThirupathiReddy Vajjala
 
PPTX
Introduction to JPA (JPA version 2.0)
ejlp12
 
PPT
test for jpa spring boot persistence hehe
AdePutraNurcholikSan
 
DOCX
Ecom lec4 fall16_jpa
Zainab Khallouf
 
PDF
Jpa
vantinhkhuc
 
PPTX
Jakarta Persistence (JPA) - Web Technologies
ssuser0562f1
 
PDF
Ejb3 Presentation
Saurabh Raisinghani
 
PDF
Introduction to Datastore
Software Park Thailand
 
ODP
JavaEE Spring Seam
Carol McDonald
 
PPTX
Doctrine ORM Internals. UnitOfWork
Illia Antypenko
 
PPT
Entity Persistence with JPA
Subin Sugunan
 
PPTX
Configuring jpa in a Spring application
Jayasree Perilakkalam
 
PPTX
Hibernate
Prashant Kalkar
 
PPTX
java framwork for HIBERNATE FRAMEWORK.pptx
ramanujsaini2001
 
PPTX
React JS; all concepts. Contains React Features, JSX, functional & Class comp...
Karmanjay Verma
 
PPTX
Hibernate Training Session1
Asad Khan
 
PDF
Java Web Programming on Google Cloud Platform [2/3] : Datastore
IMC Institute
 
PDF
Spring Boot Tutorial Part 2 (JPA&Hibernate) .pdf
abdelr7man3mad2004
 
Jpa 2.1 Application Development
ThirupathiReddy Vajjala
 
Introduction to JPA (JPA version 2.0)
ejlp12
 
test for jpa spring boot persistence hehe
AdePutraNurcholikSan
 
Ecom lec4 fall16_jpa
Zainab Khallouf
 
Jakarta Persistence (JPA) - Web Technologies
ssuser0562f1
 
Ejb3 Presentation
Saurabh Raisinghani
 
Introduction to Datastore
Software Park Thailand
 
JavaEE Spring Seam
Carol McDonald
 
Doctrine ORM Internals. UnitOfWork
Illia Antypenko
 
Entity Persistence with JPA
Subin Sugunan
 
Configuring jpa in a Spring application
Jayasree Perilakkalam
 
Hibernate
Prashant Kalkar
 
java framwork for HIBERNATE FRAMEWORK.pptx
ramanujsaini2001
 
React JS; all concepts. Contains React Features, JSX, functional & Class comp...
Karmanjay Verma
 
Hibernate Training Session1
Asad Khan
 
Java Web Programming on Google Cloud Platform [2/3] : Datastore
IMC Institute
 
Spring Boot Tutorial Part 2 (JPA&Hibernate) .pdf
abdelr7man3mad2004
 

Recently uploaded (20)

PDF
A Day in the Life of Location Data - Turning Where into How.pdf
Precisely
 
PDF
The Evolution of KM Roles (Presented at Knowledge Summit Dublin 2025)
Enterprise Knowledge
 
PDF
Google I/O Extended 2025 Baku - all ppts
HusseinMalikMammadli
 
PDF
Tea4chat - another LLM Project by Kerem Atam
a0m0rajab1
 
PPTX
What-is-the-World-Wide-Web -- Introduction
tonifi9488
 
PDF
How Open Source Changed My Career by abdelrahman ismail
a0m0rajab1
 
PDF
Security features in Dell, HP, and Lenovo PC systems: A research-based compar...
Principled Technologies
 
PPTX
The-Ethical-Hackers-Imperative-Safeguarding-the-Digital-Frontier.pptx
sujalchauhan1305
 
PDF
Accelerating Oracle Database 23ai Troubleshooting with Oracle AHF Fleet Insig...
Sandesh Rao
 
PPTX
AI and Robotics for Human Well-being.pptx
JAYMIN SUTHAR
 
PDF
Using Anchore and DefectDojo to Stand Up Your DevSecOps Function
Anchore
 
PDF
The Future of Mobile Is Context-Aware—Are You Ready?
iProgrammer Solutions Private Limited
 
PPTX
AI in Daily Life: How Artificial Intelligence Helps Us Every Day
vanshrpatil7
 
PDF
AI-Cloud-Business-Management-Platforms-The-Key-to-Efficiency-Growth.pdf
Artjoker Software Development Company
 
PDF
Oracle AI Vector Search- Getting Started and what's new in 2025- AIOUG Yatra ...
Sandesh Rao
 
PDF
Get More from Fiori Automation - What’s New, What Works, and What’s Next.pdf
Precisely
 
PPTX
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
PDF
Economic Impact of Data Centres to the Malaysian Economy
flintglobalapac
 
PPTX
Applied-Statistics-Mastering-Data-Driven-Decisions.pptx
parmaryashparmaryash
 
PDF
A Strategic Analysis of the MVNO Wave in Emerging Markets.pdf
IPLOOK Networks
 
A Day in the Life of Location Data - Turning Where into How.pdf
Precisely
 
The Evolution of KM Roles (Presented at Knowledge Summit Dublin 2025)
Enterprise Knowledge
 
Google I/O Extended 2025 Baku - all ppts
HusseinMalikMammadli
 
Tea4chat - another LLM Project by Kerem Atam
a0m0rajab1
 
What-is-the-World-Wide-Web -- Introduction
tonifi9488
 
How Open Source Changed My Career by abdelrahman ismail
a0m0rajab1
 
Security features in Dell, HP, and Lenovo PC systems: A research-based compar...
Principled Technologies
 
The-Ethical-Hackers-Imperative-Safeguarding-the-Digital-Frontier.pptx
sujalchauhan1305
 
Accelerating Oracle Database 23ai Troubleshooting with Oracle AHF Fleet Insig...
Sandesh Rao
 
AI and Robotics for Human Well-being.pptx
JAYMIN SUTHAR
 
Using Anchore and DefectDojo to Stand Up Your DevSecOps Function
Anchore
 
The Future of Mobile Is Context-Aware—Are You Ready?
iProgrammer Solutions Private Limited
 
AI in Daily Life: How Artificial Intelligence Helps Us Every Day
vanshrpatil7
 
AI-Cloud-Business-Management-Platforms-The-Key-to-Efficiency-Growth.pdf
Artjoker Software Development Company
 
Oracle AI Vector Search- Getting Started and what's new in 2025- AIOUG Yatra ...
Sandesh Rao
 
Get More from Fiori Automation - What’s New, What Works, and What’s Next.pdf
Precisely
 
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
Economic Impact of Data Centres to the Malaysian Economy
flintglobalapac
 
Applied-Statistics-Mastering-Data-Driven-Decisions.pptx
parmaryashparmaryash
 
A Strategic Analysis of the MVNO Wave in Emerging Markets.pdf
IPLOOK Networks
 

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/