SlideShare a Scribd company logo
1
Introduction to Java Persistence API
2
Java Persistence API
• Part of JSR-220 (Enterprise JavaBeans ™ 3.0)
• Began as simplification of entity beans
 Evolved into POJO persistence technology
• JPA was defined as part of EJB3.0 as a replacement to EJB 2 CMP
Entity beans.
• It is now considered the standard industry approach for ORM
• Scope expanded a request of community to support general use in
Java ™ EE and Java SE environments
• Reference implementaion under Project GlassFish
 Oracle TopLink Essentials
3
Primary Features
• POJO-based persistence model
 Simple Java classes —no components
• Support for enriched domain modeling
 Inheritance, polymorphism,etc.
• Expanded query language
• Standardized object /relational mapping
 Using Annotations and/or XML
• Usable in Java EE and Java SE environments
• Support for pluggable persistence providers
4
Entities
• Plain old Java objects
 Created by means of new
 No required interfaces
 Have persistent identity
 May have both persistent and non-persistent state
• Simple types (e.g., primitives, wrappers, enums)
• Composite dependent object types (e.g., Address)
• Non-persistent state (transient or @Transient )
 Can extend other entity and non-entity classes
 Serializable; usable as de ached object s in other tiers
• No need for data transfer objects
5
Example
@Entity public class Customer implements Serializable {
@Id protected Long id;
protected String name;
@Embedded
protected Address address;
protected PreferredStatus status;
@Transient
protected int orderCount;
public Customer(){}
public Long getId(){return id;} protected void setId(Long id){this.id =id;}
public String getName(){return name;}
public void setName(String name){
this.name =name;
}
…
}
6
Entity Identity
• Every entity has a persistence identity
 Maps to primary key in database
• Can correspond to simple type
 Annotations
• @Id —single field/proper y in en i y class
• @GeneratedValue —value can be genera ed automatically
using various strategies (SEQUENCE,TABLE,IDENTITY,AUTO)
• Can correspond o user-defined class
 Annotations
• @EmbeddedId —single field/property in entity class
• @IdClass —corresponds to multiple Id fields in entity class
• Must be defined on root of entity hierarchy or mapped superclass
7
Persistence context
• Represent a set of managed entity instances a run time
• Entity instances all belong to same persistence unit ;all mapped to
same database
• Persistence unit is a unit of packaging and deployment
• EntityManager API is used to manage persistence context ,control
lifecycle of entities, find entities by id, create queries
8
Types of Entity Managers
• Container-managed
 A typical JTA transaction involves calls across multiple components,
which in turn, may access he same persistence context
 Hence, the persistence context has to be propagated with he JTA
transaction to avoid the need for the application to pass references to
EntityManager instances from one component to another
• Application-managed
 Application manages the life time of he EnityManager
9
Two types of container-managed entity manager
• Transaction scope entity manager
 Transaction scoped persistence context begins when entity
manager is invoked within the scope of a Transaction, and ends
when he transaction is committed or rolled-back
 If en i y manager is invoked out side a transaction, any entities
loaded from he da abase immediately become de ached a the
end of he method call
• Extended scope entity manager
 The persistence context exists from the time the entity manager
instance is created until it is closed
 Extended scope persistence context could span multiple
transactional and non-transactional invocations of he entity
manager
 Extended scope persistence context maintains references to
entities after the Transaction has commited i.e. Entities remain
managed
10
Entity Lifecycle
• new
 New entity instance is created
 Entity is not yet managed or persistent
• persist
 Entity becomes managed
 Entity becomes persistent in database on Transaction commit
• remove
 Entity is removed
 Entity is dele ed from database on transaction commit
• refresh
 Entity ’s state is reloaded from database
• merge
 State of detached entity is merged back in o managed entity
11
Entity Relationships
• One-to-one, one-to-many, many-to-many, many-to-one
relationships among entities
 Support for Collection, Set ,List ,Map types
• May be unidirectional or bidirectional
 Bidirectional relationships are managed by application, not
Container
 Bidirectional relationships have owning side and inverse side
 Unidirectional relationships only have an owning side
 Owning side determines he updates to the relationship in the
database
• When to delete related data?
12
Example
@Entity public class Customer {
@Id protected Long id;
…
@OneToMany protected Set<Order>orders =new HashSet();
@ManyToOne protected SalesRep rep;
…
public Set<Order>getOrders(){return orders;}
public SalesRep getSalesRep(){return rep;}
public void setSalesRep(SalesRep rep){this.rep =rep;}
}//
@Entity public class SalesRep {
@Id protected Long id;
…@OneToMany(mappedBy=“rep ”)
protected Set<Customer>customers =new HashSet();
…
public Set<Customer>getCustomers(){return customers;}
public void addCustomer(Customer customer){ getCustomers().add(customer);
customer.setSalesRep(this);
} }
13
Inheritance
• Entities can extend
 Other entities
• Either concrete or abstract
 Mapped superclasses
• Supply common entity state
 Ordinary (non-entity) Java classes
• Supply behavior and/or non-persistent state
14
Example
MappedSuperclass
@MappedSuperclass public class Person {
@Id protected Long id;
protected String name;
@Embedded protected Address address;
}
@Entity public class Customer extends Person {
@Transient protected int orderCount;
@OneToMany protected Set<Order>orders =new HashSet();
}
@Entity public class Employee extends Person {
@ManyToOne protected Department dept;
}
A mapped superclass cannot be a target of queries, and cannot be passed
to methods on EntityManager interface. It cannot be target of persistent
relationships.
15
Example
Abstract Entity
@Entity public abstract class Person {
@Id protected Long id;
protected String name;
@Embedded protected Address address;
}
@Entity public class Customer extends Person { @Transient protected
int orderCount;
@OneToMany protected Set<Order>orders =new HashSet();
}
@Entity public class Employee extends Person {
@ManyToOne protected Department dept;
}
An abstract entity can be a target of queries, and can be passed to
methods on EntityManager interface. It cannot be instantiated.
16
Persist
@Stateless public class OrderManagementBean implements
OrderManagement {
…
@PersistenceContext EntityManager em;
…
public Order addNewOrder(Customer customer, Product product){
Order order =new Order(product);
customer.addOrder(order);
em.persist(order);
return order;
} }
Should be able to get rid of this When we add an order to customer, an
order should automatically be inserted in the underlying orders table.
17
Cascading Persist
@Entity public class Customer {
@Id protected Long id; …
@OneToMany(cascade=PERSIST)
protected Set<Order>orders =new HashSet();
}
…
public Order addNewOrder(Customer customer, Product product){
Order order =new Order(product); customer.addOrder(order);
return order; }
Add Order into the underlying tab e at the time of adding Order to the
Customer entity's state.
18
Remove
@Entity public class Order {
@Id protected Long orderId;
…
@OneToMany(cascade={PERSIST,REMOVE}) protected
Set<LineItem>ineItems =new HashSet();
}
…
@PersistenceContext EntityManager em; …
public void de eteOrder(Long orderId){ Order order =em.find(Order.c
ass,orderId); em.remove(order);
}
Remove a the associated LineItem entities when we remove Order
entity.
19
Merge
@Entity public class Order {
@Id protected Long orderId; …
@OneToMany(cascade={PERSIST,REMOVE,MERGE})
protected Set<LineItem>ineItems =new HashSet();
}
…
@PersistenceContext EntityManager em;
…
public Order updateOrder(Order changedOrder){
return em.merge(changedOrder);
}
Propagate changes (if any)to LineItem entity upon merging the
Order entity.
20
Queries
21
Java Persistence Query Language
• An extension of EJB ™ QL
 Like EJB QL, a SQL-like language
• Added functionality
 Projection list (SELECT clause)
 Explicit JOINS
 Subqueries
 GROUP BY,HAVING
 EXISTS,ALL,SOME/ANY
 UPDATE,DELETE opera ions
 Additional functions
22
Projection
SELECT e.name, d.name FROM Employee e JOIN
e.department d WHERE e.status =‘FULLTIME ’
SELECT new com.example.EmployeeInfo(e.id, e.name,e.salary,
e.status,d.name) FROM Employee e JOIN e.department d
WHERE e.address.state =‘CA ’
23
Subqueries
SELECT DISTINCT emp FROM Employee emp WHERE EXISTS (
SELECT mgr FROM Manager mgr WHERE emp.manager =mgr
AND emp.salary >mgr.salary)
24
Joins
• SELECT DISTINCT o FROM Order o JOIN o.lineItems JOIN
.product p WHERE p.productType =‘shoes ’
• SELECT DISTINCT c FROM Customer c LEFT JOIN FETCH
c.orders WHERE c.address.city =‘San Francisco ’
25
Update,Delete
• UPDATE Employee e SET e.salary =e.salary *1.1 WHERE
e.department.name =‘Engineering ’
• DELETE FROM Customer c WHERE c.status =‘inactive ’AND
c.orders IS EMPTY AND c.balance =0
26
Queries
• Static queries
 Defined with Java language metada a or XML
• Annotations: @NamedQuery, @NamedNativeQuery
• Dynamic queries
 Query string is specified a run time
• Use Java Persistence query language or SQL
• Named or positional parameters
• EntityManager is factory for Query objects
 createNamedQuery,createQuery,createNativeQuery
• Query methods for con rolling max results, pagination,flush mode
27
Dynamic Queries
@PersistenceContext EntityManager em;
…
public List findByZipcode(String personType,
int zip){
return em.createQuery ( “SELECT p FROM ”
+personType +“ p WHERE p.address.zip =:zip ”)
.setParameter(“zipcode ”,zip)
.setMaxResults(20));
}
28
Static Query
@NamedQuery(name=“customerFindByZipcode ”, query = “SELECT c
FROM Customer c WHERE c.address.zipcode =:zip ”)
@Entity public class Customer {…}
…
public List findCustomerByZipcode(int zipcode){
return em.createNamedQuery (“customerFindByZipcode ”)
.setParameter(“zip ”,zipcode).setMaxResu ts(20).getResutList();
}

More Related Content

PPTX
JPA For Beginner's
PPTX
Jakarta Persistence (JPA) - Web Technologies
PDF
20160523 hibernate persistence_framework_and_orm
PDF
Introduction to Datastore
PPTX
HIBERNATE For Databases java presentation.pptx
PDF
PPTX
Jpa 2.1 Application Development
PDF
Java Persistence API 2.0: An Overview
JPA For Beginner's
Jakarta Persistence (JPA) - Web Technologies
20160523 hibernate persistence_framework_and_orm
Introduction to Datastore
HIBERNATE For Databases java presentation.pptx
Jpa 2.1 Application Development
Java Persistence API 2.0: An Overview

Similar to test for jpa spring boot persistence hehe (20)

PDF
Java Web Programming on Google Cloud Platform [2/3] : Datastore
PDF
Using the latest Java Persistence API 2 Features - Tech Days 2010 India
PDF
.Net template solution architecture
PDF
Code decoupling from Symfony (and others frameworks) - PHP Conference Brasil ...
PDF
S313431 JPA 2.0 Overview
PDF
springdatajpa-up.pdf
PDF
Ejb3 Presentation
PPTX
Spring data jpa
PDF
Five android architecture
PDF
Java unit 7
PPT
PDF
JAVA Class Presentation.pdf Vsjsjsnheheh
DOCX
Design PatternsEECS 3311Song Wang[email protected]ee
PPTX
java framwork for HIBERNATE FRAMEWORK.pptx
PPTX
Summer industrial trainingnew
PPTX
Context and Dependency Injection 2.0
PDF
C# Advanced L07-Design Patterns
PDF
Android meetup
ODP
Jpa buenas practicas
ODP
JPA Best Practices
Java Web Programming on Google Cloud Platform [2/3] : Datastore
Using the latest Java Persistence API 2 Features - Tech Days 2010 India
.Net template solution architecture
Code decoupling from Symfony (and others frameworks) - PHP Conference Brasil ...
S313431 JPA 2.0 Overview
springdatajpa-up.pdf
Ejb3 Presentation
Spring data jpa
Five android architecture
Java unit 7
JAVA Class Presentation.pdf Vsjsjsnheheh
Design PatternsEECS 3311Song Wang[email protected]ee
java framwork for HIBERNATE FRAMEWORK.pptx
Summer industrial trainingnew
Context and Dependency Injection 2.0
C# Advanced L07-Design Patterns
Android meetup
Jpa buenas practicas
JPA Best Practices
Ad

Recently uploaded (20)

PDF
Understanding Forklifts - TECH EHS Solution
PDF
PTS Company Brochure 2025 (1).pdf.......
PDF
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
PDF
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
PPTX
ai tools demonstartion for schools and inter college
PDF
How to Migrate SBCGlobal Email to Yahoo Easily
PDF
Softaken Excel to vCard Converter Software.pdf
PPTX
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
PPTX
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
PPTX
L1 - Introduction to python Backend.pptx
PDF
System and Network Administration Chapter 2
PDF
Wondershare Filmora 15 Crack With Activation Key [2025
PPTX
Operating system designcfffgfgggggggvggggggggg
PDF
How Creative Agencies Leverage Project Management Software.pdf
PPTX
Odoo POS Development Services by CandidRoot Solutions
PDF
System and Network Administraation Chapter 3
PDF
Digital Strategies for Manufacturing Companies
PDF
top salesforce developer skills in 2025.pdf
PDF
Raksha Bandhan Grocery Pricing Trends in India 2025.pdf
PDF
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
Understanding Forklifts - TECH EHS Solution
PTS Company Brochure 2025 (1).pdf.......
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
ai tools demonstartion for schools and inter college
How to Migrate SBCGlobal Email to Yahoo Easily
Softaken Excel to vCard Converter Software.pdf
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
L1 - Introduction to python Backend.pptx
System and Network Administration Chapter 2
Wondershare Filmora 15 Crack With Activation Key [2025
Operating system designcfffgfgggggggvggggggggg
How Creative Agencies Leverage Project Management Software.pdf
Odoo POS Development Services by CandidRoot Solutions
System and Network Administraation Chapter 3
Digital Strategies for Manufacturing Companies
top salesforce developer skills in 2025.pdf
Raksha Bandhan Grocery Pricing Trends in India 2025.pdf
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
Ad

test for jpa spring boot persistence hehe

  • 1. 1 Introduction to Java Persistence API
  • 2. 2 Java Persistence API • Part of JSR-220 (Enterprise JavaBeans ™ 3.0) • Began as simplification of entity beans  Evolved into POJO persistence technology • JPA was defined as part of EJB3.0 as a replacement to EJB 2 CMP Entity beans. • It is now considered the standard industry approach for ORM • Scope expanded a request of community to support general use in Java ™ EE and Java SE environments • Reference implementaion under Project GlassFish  Oracle TopLink Essentials
  • 3. 3 Primary Features • POJO-based persistence model  Simple Java classes —no components • Support for enriched domain modeling  Inheritance, polymorphism,etc. • Expanded query language • Standardized object /relational mapping  Using Annotations and/or XML • Usable in Java EE and Java SE environments • Support for pluggable persistence providers
  • 4. 4 Entities • Plain old Java objects  Created by means of new  No required interfaces  Have persistent identity  May have both persistent and non-persistent state • Simple types (e.g., primitives, wrappers, enums) • Composite dependent object types (e.g., Address) • Non-persistent state (transient or @Transient )  Can extend other entity and non-entity classes  Serializable; usable as de ached object s in other tiers • No need for data transfer objects
  • 5. 5 Example @Entity public class Customer implements Serializable { @Id protected Long id; protected String name; @Embedded protected Address address; protected PreferredStatus status; @Transient protected int orderCount; public Customer(){} public Long getId(){return id;} protected void setId(Long id){this.id =id;} public String getName(){return name;} public void setName(String name){ this.name =name; } … }
  • 6. 6 Entity Identity • Every entity has a persistence identity  Maps to primary key in database • Can correspond to simple type  Annotations • @Id —single field/proper y in en i y class • @GeneratedValue —value can be genera ed automatically using various strategies (SEQUENCE,TABLE,IDENTITY,AUTO) • Can correspond o user-defined class  Annotations • @EmbeddedId —single field/property in entity class • @IdClass —corresponds to multiple Id fields in entity class • Must be defined on root of entity hierarchy or mapped superclass
  • 7. 7 Persistence context • Represent a set of managed entity instances a run time • Entity instances all belong to same persistence unit ;all mapped to same database • Persistence unit is a unit of packaging and deployment • EntityManager API is used to manage persistence context ,control lifecycle of entities, find entities by id, create queries
  • 8. 8 Types of Entity Managers • Container-managed  A typical JTA transaction involves calls across multiple components, which in turn, may access he same persistence context  Hence, the persistence context has to be propagated with he JTA transaction to avoid the need for the application to pass references to EntityManager instances from one component to another • Application-managed  Application manages the life time of he EnityManager
  • 9. 9 Two types of container-managed entity manager • Transaction scope entity manager  Transaction scoped persistence context begins when entity manager is invoked within the scope of a Transaction, and ends when he transaction is committed or rolled-back  If en i y manager is invoked out side a transaction, any entities loaded from he da abase immediately become de ached a the end of he method call • Extended scope entity manager  The persistence context exists from the time the entity manager instance is created until it is closed  Extended scope persistence context could span multiple transactional and non-transactional invocations of he entity manager  Extended scope persistence context maintains references to entities after the Transaction has commited i.e. Entities remain managed
  • 10. 10 Entity Lifecycle • new  New entity instance is created  Entity is not yet managed or persistent • persist  Entity becomes managed  Entity becomes persistent in database on Transaction commit • remove  Entity is removed  Entity is dele ed from database on transaction commit • refresh  Entity ’s state is reloaded from database • merge  State of detached entity is merged back in o managed entity
  • 11. 11 Entity Relationships • One-to-one, one-to-many, many-to-many, many-to-one relationships among entities  Support for Collection, Set ,List ,Map types • May be unidirectional or bidirectional  Bidirectional relationships are managed by application, not Container  Bidirectional relationships have owning side and inverse side  Unidirectional relationships only have an owning side  Owning side determines he updates to the relationship in the database • When to delete related data?
  • 12. 12 Example @Entity public class Customer { @Id protected Long id; … @OneToMany protected Set<Order>orders =new HashSet(); @ManyToOne protected SalesRep rep; … public Set<Order>getOrders(){return orders;} public SalesRep getSalesRep(){return rep;} public void setSalesRep(SalesRep rep){this.rep =rep;} }// @Entity public class SalesRep { @Id protected Long id; …@OneToMany(mappedBy=“rep ”) protected Set<Customer>customers =new HashSet(); … public Set<Customer>getCustomers(){return customers;} public void addCustomer(Customer customer){ getCustomers().add(customer); customer.setSalesRep(this); } }
  • 13. 13 Inheritance • Entities can extend  Other entities • Either concrete or abstract  Mapped superclasses • Supply common entity state  Ordinary (non-entity) Java classes • Supply behavior and/or non-persistent state
  • 14. 14 Example MappedSuperclass @MappedSuperclass public class Person { @Id protected Long id; protected String name; @Embedded protected Address address; } @Entity public class Customer extends Person { @Transient protected int orderCount; @OneToMany protected Set<Order>orders =new HashSet(); } @Entity public class Employee extends Person { @ManyToOne protected Department dept; } A mapped superclass cannot be a target of queries, and cannot be passed to methods on EntityManager interface. It cannot be target of persistent relationships.
  • 15. 15 Example Abstract Entity @Entity public abstract class Person { @Id protected Long id; protected String name; @Embedded protected Address address; } @Entity public class Customer extends Person { @Transient protected int orderCount; @OneToMany protected Set<Order>orders =new HashSet(); } @Entity public class Employee extends Person { @ManyToOne protected Department dept; } An abstract entity can be a target of queries, and can be passed to methods on EntityManager interface. It cannot be instantiated.
  • 16. 16 Persist @Stateless public class OrderManagementBean implements OrderManagement { … @PersistenceContext EntityManager em; … public Order addNewOrder(Customer customer, Product product){ Order order =new Order(product); customer.addOrder(order); em.persist(order); return order; } } Should be able to get rid of this When we add an order to customer, an order should automatically be inserted in the underlying orders table.
  • 17. 17 Cascading Persist @Entity public class Customer { @Id protected Long id; … @OneToMany(cascade=PERSIST) protected Set<Order>orders =new HashSet(); } … public Order addNewOrder(Customer customer, Product product){ Order order =new Order(product); customer.addOrder(order); return order; } Add Order into the underlying tab e at the time of adding Order to the Customer entity's state.
  • 18. 18 Remove @Entity public class Order { @Id protected Long orderId; … @OneToMany(cascade={PERSIST,REMOVE}) protected Set<LineItem>ineItems =new HashSet(); } … @PersistenceContext EntityManager em; … public void de eteOrder(Long orderId){ Order order =em.find(Order.c ass,orderId); em.remove(order); } Remove a the associated LineItem entities when we remove Order entity.
  • 19. 19 Merge @Entity public class Order { @Id protected Long orderId; … @OneToMany(cascade={PERSIST,REMOVE,MERGE}) protected Set<LineItem>ineItems =new HashSet(); } … @PersistenceContext EntityManager em; … public Order updateOrder(Order changedOrder){ return em.merge(changedOrder); } Propagate changes (if any)to LineItem entity upon merging the Order entity.
  • 21. 21 Java Persistence Query Language • An extension of EJB ™ QL  Like EJB QL, a SQL-like language • Added functionality  Projection list (SELECT clause)  Explicit JOINS  Subqueries  GROUP BY,HAVING  EXISTS,ALL,SOME/ANY  UPDATE,DELETE opera ions  Additional functions
  • 22. 22 Projection SELECT e.name, d.name FROM Employee e JOIN e.department d WHERE e.status =‘FULLTIME ’ SELECT new com.example.EmployeeInfo(e.id, e.name,e.salary, e.status,d.name) FROM Employee e JOIN e.department d WHERE e.address.state =‘CA ’
  • 23. 23 Subqueries SELECT DISTINCT emp FROM Employee emp WHERE EXISTS ( SELECT mgr FROM Manager mgr WHERE emp.manager =mgr AND emp.salary >mgr.salary)
  • 24. 24 Joins • SELECT DISTINCT o FROM Order o JOIN o.lineItems JOIN .product p WHERE p.productType =‘shoes ’ • SELECT DISTINCT c FROM Customer c LEFT JOIN FETCH c.orders WHERE c.address.city =‘San Francisco ’
  • 25. 25 Update,Delete • UPDATE Employee e SET e.salary =e.salary *1.1 WHERE e.department.name =‘Engineering ’ • DELETE FROM Customer c WHERE c.status =‘inactive ’AND c.orders IS EMPTY AND c.balance =0
  • 26. 26 Queries • Static queries  Defined with Java language metada a or XML • Annotations: @NamedQuery, @NamedNativeQuery • Dynamic queries  Query string is specified a run time • Use Java Persistence query language or SQL • Named or positional parameters • EntityManager is factory for Query objects  createNamedQuery,createQuery,createNativeQuery • Query methods for con rolling max results, pagination,flush mode
  • 27. 27 Dynamic Queries @PersistenceContext EntityManager em; … public List findByZipcode(String personType, int zip){ return em.createQuery ( “SELECT p FROM ” +personType +“ p WHERE p.address.zip =:zip ”) .setParameter(“zipcode ”,zip) .setMaxResults(20)); }
  • 28. 28 Static Query @NamedQuery(name=“customerFindByZipcode ”, query = “SELECT c FROM Customer c WHERE c.address.zipcode =:zip ”) @Entity public class Customer {…} … public List findCustomerByZipcode(int zipcode){ return em.createNamedQuery (“customerFindByZipcode ”) .setParameter(“zip ”,zipcode).setMaxResu ts(20).getResutList(); }