SlideShare a Scribd company logo
Java Persistence, JPA 2
Fahad R. Golra
ECE Paris Ecole d'Ingénieurs - FRANCE
Lecture 8 - Java Persistence,
JPA 2
• Introduction to Persistence
• Entity Beans
• Life cycle of Entity Beans
• Associations
• Entity Beans: Query Language
2 JEE - Java Persistence, JPA 2.x
Introduction to Entity Beans
• Entity Bean
• Persistent objects stored in the database
• Persistence
• by serialization
• by object - relational database mapping
• Serialization
• Saving the state of an object in the form of bytes
• An object can be reconstructed once serialized
• No complex queries, hard to maintain
3 JEE - Java Persistence, JPA 2.x
Persistence by mapping objects to
relational databases
• State of the object is store in a database
• For example: a book object has the attributes
names and isbn. We map them to a table which has
two columns: name and isbn.
• Every object is decomposed into multiple variables,
and their values are then stored in one or more tables.
• Allows complex queries
• SQL is hard to test/debug
4 JEE - Java Persistence, JPA 2.x
Persistence by mapping objects to
relational databases
5
Object Databases
• Object databases (also known as object-oriented
database management systems) can store the objects
directly to databases.
• No mapping !!!
• Object Query Language (OQL) can be used to
manipulate objects
• Easy to use, but not scalable.
6 JEE - Java Persistence, JPA 2.x
Persistence through JPA 2
• JPA 2 proposes a standard model of persistence
through the use of Entity Beans
• Tools that ensure this persistence are integrated with
the application servers and must be compatible to JPA
2 standard
• e.g. Toplink, Hibernate, EclipseLink
• Java EE permits the use of dependency injection
through annotations on all the layers.
7 JEE - Java Persistence, JPA 2.x
What is an Entity Bean?
• An object that is mapped to a database
• It uses the persistence mechanisms
• It serves to represent the data placed in the database
as objects
• An object = one or more rows in one or more tables
in the database
• Example
• A student entity is represented by a row of data in
student table of a database
8 JEE - Java Persistence, JPA 2.x
Why an Entity Bean?
• Easy to manipulate by programs
• Instance of Account entity
• A compact view of grouped data in an object
• Account object gives access to all public variables
• Associating methods to manipulate the data
• methods can be written to add behavior to Account
• The data in the database will be updated automatically
• Instance of an entity bean is a view in memory of
physical data
9 JEE - Java Persistence, JPA 2.x
Entity Bean
• Entity Bean is a POJO with attributes, getters &
setters.
• These attributes are mapped to database tables
• We use annotations to define the mapping to
attributes
• Primary Key, is a serializable object
• Attributes of annotations to customize the mapping
10 JEE - Java Persistence, JPA 2.x
Persistent Fields and Properties
• Java primitive types
• java.lang.String
• Other serializable types, including:
• Wrappers of Java primitive types
• java.math.BigInteger
• java.math.BigDecimal
• java.util.Date
• java.util.Calendar
• java.sql.Date
• java.sql.Time
11
• java.sql.TimeStamp
• User-defined serializable types
• byte[]
• Byte[]
• char[]
• Character[]
• Enumerated types
• Other entities and/or collections of
entities
• Embeddable classes
Example: Entity Bean (Book)
@Entity
public class Book implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue
private Long id;
@Column(nullable = false)
private String title;
private Float price;
@Column(length = 2000)
private String description;
private String isbn;
private Integer nbOfPage;
private Boolean illustrations;
// Constructors, getters, setters
}
12
Example Entity Bean: Book
13 JEE - Java Persistence, JPA 2.x
Entity Manager
• We manipulate the data in the database with the help
of Entity Beans and a Entity Manager
• Entity Manager is responsible of access the disks,
caches, etc.
• Entity Manager controls when and how we can access
the database.
• It generates the SQL.
14 JEE - Java Persistence, JPA 2.x
Example: Client (Inserting a Book)
public class BookHandler {
public static void main(String[] args) {
Book book = new Book();
book.setTitle("The Hitchhiker's Guide to the Galaxy");
book.setPrice(12.5F);
book.setDescription("Science fiction comedy book”);
// set other fields as well . . .
// Get a pointer to entity manager. We don't need to do this in web app!
EntityManagerFactory emf = Persistence
.createEntityManagerFactory("chapter02PU");
EntityManager em = emf.createEntityManager();
// Persisting the object in a transaction
EntityTransaction tx = em.getTransaction();
tx.begin();
em.persist(book);
tx.commit();
em.close();
emf.close();
}}
15
Session Bean as a Client
• In such a case
• Dependency injection can be used
• Transactions are started by default
@Stateless
@LocalBean
public class MySessionBean {
EntityManager em;
public Employee createEmployee(int id, String name, long salary) {
Employee emp = new Employee(id);
emp.setName(name);
…..
em.persist(emp);
return emp;
}
}
16 JEE - Java Persistence, JPA 2.x
Session Bean as a Client
17
@Stateless
public class BookBean {
@PersistenceContext(unitName = "bookLib")
private EntityManager em;
public void createBook() {
Book book = new Book();
book.setId(1234L);
book.setTitle("The Alpha Book");
book.setPrice(13.5F);
book.setDescription("Description of my book");
book.setIsbn("1-465-65465");
book.setNbOfPage(230);
book.setIllustrations(false);
em.persist(book);
book = em.find(Book.class, 1234L);
System.out.println(book);
}}
Why use session beans?
• They are used to implement the business logic
• A session bean can be used to implement Data
Access Object (DAO)
• DAO offers the functions of creation, searching,
modification and deletion of entity beans.
• Session beans can also be used to implement
composite services.
18 JEE - Java Persistence, JPA 2.x
Other Annotations
@Entity
public class Book implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(name = "book_title", nullable = false, updatable = false)
private String title;
private Float price;
@Column(length = 2000)
private String description;
private String isbn;
@Column(name = "nb_of_page", nullable = false)
private Integer nbOfPage;
@Basic(fetch = FetchType.LAZY)
@Lob
private Boolean illustrations;
// Constructors, getters, setters
}
19
Other Annotations
• @Column
• allows the preferences for columns
• Attributes: name, unique, nullable, insertable,
updatable, length, ….
• @Generated Value
• indicates the strategy for the automatic generation
of primary keys
• It depends on the database being used, so
automatic is recommended
20 JEE - Java Persistence, JPA 2.x
Other Annotations
• @Lob
• indicates “large object” for a BLOB
• Often used with @Basic(fetch=FetchType.LAZY) for
indicating that we want this attribute to be loaded
only when a get is used on it.
• There are many other annotations.
• Java EE 7 specification can be consulted for it.
21 JEE - Java Persistence, JPA 2.x
Example: Persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
version="1.0">
<persistence-unit name="JPA_first">
<provider>oracle.toplink.essentials.PersistenceProvider</provider>
<class>com.ece.jee.entities.Client</class>
<properties>
<property name="toplink.jdbc.driver" value="com.mysql.jdbc.Driver" /
>
<property name="toplink.jdbc.url" value="jdbc:mysql://localhost:
3306/ece_db" />
<property name="toplink.jdbc.user" value="root" />
<property name="toplink.jdbc.password" value="secret" />
<property name="toplink.target-database" value="MySQL4" />
<property name="toplink.ddl-generation" value="drop-and-create-
tables" />
<property name="toplink.ddl-generation.output-mode" value="both" />
<property name="toplink.logging.level" value="FINE" />
</properties>
</persistence-unit>
</persistence>
22
Persistence Context
• A persistence context is a set of entity instances in
which for every persistent entity identity there is a
unique entity instance.
• The entity instances and their lifecycle are managed
within the persistence context.
• The EntityManager API is used to create and remove
persistent entity instances, to find entities by their
primary keys, and to query over entities.
23 JEE - Java Persistence, JPA 2.x
Life cycle of Entity Bean
24 JEE - Java Persistence, JPA 2.x
Life cycle of Entity Bean
• New: The bean exists in the memory but is not
mapped to DB yet. It is not yet mapped to persistence
context (via entity manager)
• Managed: The bean is mapped to the DB. The
changes effect the data in DB.
• Detached: The bean is not mapped to the persistence
context anymore.
• Removed: The bean is still mapped to the persistence
context and the DB, but it is programmed to be
deleted.
25 JEE - Java Persistence, JPA 2.x
Life cycle of Entity Bean
• remove(): To delete the data
• set(), get(): If the bean is in managed state, these
methods (of the entity bean) are used to access or
modify the data.
• persist(): To create the data. The bean goes to
managed state.
• merge(): To take a bean from detached state to a
managed state.
26 JEE - Java Persistence, JPA 2.x
Entity Manager example methods
public Account openAccount(String ownerName) {
Account account = new Account();
account.ownerNamer = ownerName;
em.persist(account); // attach the bean & persist
return account; // copy is detached
}
public void update(Account detachedAccount) {
Account managedAccount = em.merge(detachedAccount);
}
public void delete(Account detachedAccount) {
Account managedAccount = em.merge(detachedAccount);
em.remove(managedAccount);
}
public void findAccount(int id) {
return em.find(Account.class, Integer.valueOf(id));
}
27
Entity Manager (other principal methods)
Object find(Class cl, Object key) :
• Find an EntityBean by its id
boolean contains(Object entity) :
• True if the entity is attached to the EntityManager
Query createQuery(String sqlString) :
• Creating a query in EJB-QL
Query createNamedQuery(String name) :
• Creating a named query
Query createNativeQuery(String sqlQuery) :
• Creating an SQL query
void refresh(Object entity) :
• Recharging the bean from the DB
28 JEE - Java Persistence, JPA 2.x
Using composite columns
• Fields of two classes into one table
@Embeddable
public class Address {
private String street;
private int postalCode;
}
@Entity
public class User {
private String name;
@Embedded
private Address address;
}
29
Composite Primary Key
• Instead of using @Embedded we use @EmbeddedId for
composite primary keys
@Embeddable
public class CompositeId {
private String name;
private String email;
}
@Entity
public class Dependent {
@EmbeddedId
CompositeId id;
@ManyToOne
Employee emp;
}
30
Associations
• Cardinality
• 1 - 1 (one to one): one employee has one address
• 1 - n (one to many): one employee has multiple addresses
• n - 1 (many to one): multiple employees have one address
• n - n (many to many): multiple employees have multiple
addresses
• Direction (navigability)
• Unidirectional:
• we can go from bean A to bean B only
• Bi-directional:
• we can go from bean A to bean B & vice-versa
31 JEE - Java Persistence, JPA 2.x
Unidirectional: OneToOne
• Employee entity -> ︎Employee table
• Address entity -> ︎Address table with address_Id as PK
• Employee table owns a foreign key to Address, address
@Entity
public class Employee {
private Address address;
@OneToOne
public Address getAddress() {
return address;
}
public void setAddress(Address ad) {
this.address = ad;
}
}
32
@Entity
public class Address {
…
}
Employee Address
1 1
adress
Unidirectional: ManyToOne
• Employee entity -> ︎Employee table
• Address entity -> ︎Address table with address_Id as PK
• Employee table owns a foreign key to Address, address
@Entity
public class Employee {
private Address address;
@ManyToOne
public Address getAddress() {
return address;
}
public void setAddress(Address ad) {
this.address = ad;
}
}
33
@Entity
public class Address {
…
}
Employee Address
0..* 1
adress
Unidirectional: OneToMany
• Employee entity -> ︎Employee table
• Address entity -> ︎Address table with address_Id as PK
• Creation of a join table Employee_Address with two columns (i.e.
Employee_Pkemployee & Address_PKAddress, each column
represents a PK to each table
@Entity
public class Employee {
private Collection<Address> addresses;
@OneToMany
public Collection<Address> getAddresses() {
return addresses;
}
public void setAddresses(Collection<Address> addresses) {
this.addresses = addresses;
}
}34
@Entity
public class Address {
…
}
Employee Address
1 0..*
adresses
Unidirectional: ManyToMany
• Employee entity -> ︎Employee table
• Address entity -> ︎Address table with address_Id as PK
• Creation of a join table Employee_Address with two columns (i.e.
Employee_Pkemployee & Address_PKAddress, each column
represents a PK to each table
@Entity
public class Employee {
private Collection<Address> addresses;
@ManyToMany
public Collection<Address> getAddresses() {
return addresses;
}
public void setAddresses(Collection<Address> addresses) {
this.addresses = addresses;
}
}
35
@Entity
public class Address {
…
}
Employee Address
0..* 0..*
adresses
Bi-directional: OneToOne
• Employee entity -> ︎Employee table
• Cashier entity -> ︎Cashier table with myCashier_Id as PK
• Employee table owns a foreign key to Cashier, myCashier
(note: Cashier will not have a foreign key to Employee)
36
@Entity
public class Cashier {
private Employee myEmployee;
@OneToOne(mappedBy = "myCashier")
public Employee getMyEmployee() {
return myEmployee;
}
public void setMyEmploye(Employee e) {
this.myEmployee = e;
}
}
@Entity
public class Employee {
private Cashier myCashier;
@OneToOne
public Cashier getMyCashier() {
return myCashier;
}
public void setMyCashier(Cashier c) {
this.myCashier = c;
}
}
Employee Cashier
1 1
myCashiermyEmployee
Bi-directional: ManyToOne/OneToMany
• Employee entity -> ︎Employee table
• Cashier entity -> ︎Cashier table with myCashier_Id as PK
• Employee table owns a foreign key to Cashier, myCashier
(note: Cashier will not have a foreign key to Employee)
37
@Entity
public class Cashier {
private Collection<Employee> myEmployees;
@OneToMany(mappedBy = "myCashier")
public Collection<Employee>
getMyEmployees() {
return myEmployees;
}
public void
setMyEmployees(Collection<Employee> e) {
this.myEmployees = e;
}
}
@Entity
public class Employee {
private Cashier myCashier;
@ManyToOne
public Cashier getMyCashier() {
return myCashier;
}
public void setMyCashier(Cashier c) {
this.myCashier = c;
}
}
Employee Cashier
0..* 1
myCashiermyEmployees
Bi-directional: ManyToMany
• Employee entity -> ︎Employee table
• Cashier entity -> ︎Cashier table
• Creation of a join table Project_Employee with two columns (i.e.
myProjects_PKProject & myEmployees_PkEmployee, each
column represents a PK to each table
38
@Entity
public class Employee {
private Collection<Project> myProjects;
@ManyToMany(mappedBy = "myEmployees")
public Collection<Project> getMyProjets()
{
return myProjects;
}
public void
setMyProjets(Collection<Project> p) {
this.myProjects = p;
}
}
@Entity
public class Project {
Collection<Employee> myEmployees;
@ManyToMany
public Collection<Employee>
getMesEmployees() {
return myEmployees;
}
public void
setMesEmployes(Collection<Employee> e) {
this.myEmployees = e;
}
}
Project Employee
0..* 0..*
myEmployeesmyProjects
Entity Bean Inheritance
• Entities support inheritance and polymorphism
• Entities may be concrete or abstract
@Entity
public abstract class Person {
@Id
protected String name; …
}
@Entity
public class Employee extends Person {
protected float salary; …
}
39 JEE - Java Persistence, JPA 2.x
Inheritance Strategies
• One Table by classes hierarchy (Default) :
@Inheritance(strategy=SINGLE_TABLE)
• Implemented in most tooling solutions
• Good support of polymorphism
• Columns proper to sub-classes set at null
• One Table by concrete class:
@Inheritance(strategy=TABLE_PER_CLASS)
• Some issues remain regarding polymorphism
• Join Strategy:
• @Inheritance(strategy=JOINED)
• a join between the concrete class and the super class tables
• Good support of polymorphism
• Not always implemented
• Join operation can be costly
40 JEE - Java Persistence, JPA 2.x
Entity Bean Inheritance
• An Entity can inherit a non-entity class and vice-versa
• MappedSuperClasses are not accessible to EntityManager
• Not considered as Entity (no table in DB)
@MappedSuperclass
public abstract class Person {
protected Date dob;
}
@Entity
public class Employee extends Person {
@Id
protected int id;
protected String name;
}
41 JEE - Java Persistence, JPA 2.x
Entity Bean Compliments
• Fetch: option for loading the graph of objects
• FetchType.EAGER : loads all the tree (required if Serializable) ︎
• FetchType.LAZY : only on demand (unusable with Serializable)
• Cascade: transitivity of operations over the beans
• CascadeType.ALL: every operation is propagated
• CascadeType.MERGE: in case of a merge
• CascadeType.PERSIST: When film Entity becomes
persistent, then List<Cinema> too
• CascadeType.REFRESH: loading from the DB
• ︎CascadeType.REMOVE: delete in cascade
42 JEE - Java Persistence, JPA 2.x
Entity Beans: Query Language
• parameters indicated by :param-name
• Request in Query object
• Result from Query object
• getResultList()
• getSingleResult()
43 JEE - Java Persistence, JPA 2.x
Entity Beans: Named Query
• Named query can be attached to the Entity Bean
44 JEE - Java Persistence, JPA 2.x
Entity Beans: Native Query
• SQL queries can be used using
• createNativeQuery(String sqlString)
• createNativeQuery(String sqlString, Class resultClass)
45 JEE - Java Persistence, JPA 2.x
Entity Beans: Life cycle interceptors
• Interception of state changes
• Around the creation (em.persist) : ︎
• @PrePersist
• @PostPersist
• At loading time from DB (em.find, Query.getResultList)
• @PostLoad
• Around updates (modification of a field, em.merge) ︎
• @PreUpdate
• @PostUpdate
• Around a remove action (em.remove) ︎
• @PreRemove
• @PostRemove
46
References
• Some of the slide contents are take
from the slides of
• Reda Bendraou, UPMC
• Michel Buffa, UNSA
47 JEE - Java Persistence, JPA 2.x
48 JEE - Java Persistence, JPA 2.x

More Related Content

What's hot (19)

PDF
Java Web Programming [3/9] : Servlet Advanced
IMC Institute
 
PPTX
Hibernate
Prashant Kalkar
 
PPS
Java Hibernate Programming with Architecture Diagram and Example
kamal kotecha
 
PPSX
Spring - Part 3 - AOP
Hitesh-Java
 
PPSX
Java IO, Serialization
Hitesh-Java
 
PDF
Contextual Dependency Injection for Apachecon 2010
Rohit Kelapure
 
PDF
Java Web Programming [4/9] : JSP Basic
IMC Institute
 
PDF
jsf2 Notes
Rajiv Gupta
 
DOC
24 collections framework interview questions
Arun Vasanth
 
PDF
Hibernate 3
Rajiv Gupta
 
PDF
Understanding
Arun Gupta
 
PPSX
JSP - Part 1
Hitesh-Java
 
PDF
Spring design-juergen-qcon
Yiwei Ma
 
PPTX
Advance java1.1
Prince Soni
 
PDF
Introduction to JPA and Hibernate including examples
ecosio GmbH
 
PPSX
JSP - Part 2 (Final)
Hitesh-Java
 
PPSX
Struts 2 - Introduction
Hitesh-Java
 
PPSX
Hibernate - Part 2
Hitesh-Java
 
PDF
Java Web Programming [7/9] : Struts2 Basics
IMC Institute
 
Java Web Programming [3/9] : Servlet Advanced
IMC Institute
 
Hibernate
Prashant Kalkar
 
Java Hibernate Programming with Architecture Diagram and Example
kamal kotecha
 
Spring - Part 3 - AOP
Hitesh-Java
 
Java IO, Serialization
Hitesh-Java
 
Contextual Dependency Injection for Apachecon 2010
Rohit Kelapure
 
Java Web Programming [4/9] : JSP Basic
IMC Institute
 
jsf2 Notes
Rajiv Gupta
 
24 collections framework interview questions
Arun Vasanth
 
Hibernate 3
Rajiv Gupta
 
Understanding
Arun Gupta
 
JSP - Part 1
Hitesh-Java
 
Spring design-juergen-qcon
Yiwei Ma
 
Advance java1.1
Prince Soni
 
Introduction to JPA and Hibernate including examples
ecosio GmbH
 
JSP - Part 2 (Final)
Hitesh-Java
 
Struts 2 - Introduction
Hitesh-Java
 
Hibernate - Part 2
Hitesh-Java
 
Java Web Programming [7/9] : Struts2 Basics
IMC Institute
 

Viewers also liked (20)

PDF
Lecture 7 Web Services JAX-WS & JAX-RS
Fahad Golra
 
PDF
Lecture 10 - Java Server Faces (JSF)
Fahad Golra
 
PDF
Lecture 8 Enterprise Java Beans (EJB)
Fahad Golra
 
PDF
Tutorial 4 - Basics of Digital Photography
Fahad Golra
 
PDF
Lecture 3: Servlets - Session Management
Fahad Golra
 
PDF
Enterprise Java Beans - EJB
Peter R. Egli
 
PDF
Tutorial 3 - Basics of Digital Photography
Fahad Golra
 
PDF
Tutorial 1 - Basics of Digital Photography
Fahad Golra
 
PDF
Tutorial 2 - Basics of Digital Photography
Fahad Golra
 
PDF
TNAPS 3 Installation
tncor
 
PPT
Ejb in java. part 1.
Asya Dudnik
 
PDF
2012-12-01 03 Битва ORM: Hibernate vs MyBatis. Давайте жить дружно!
Омские ИТ-субботники
 
PDF
Lazy vs. Eager Loading Strategies in JPA 2.1
Patrycja Wegrzynowicz
 
PDF
Apache Lucene + Hibernate = Hibernate Search
Vitebsk Miniq
 
ODP
Interoperable Web Services with JAX-WS
Carol McDonald
 
PPS
JPA - Java Persistence API
Thomas Wöhlke
 
PDF
Hibernate ORM: Tips, Tricks, and Performance Techniques
Brett Meyer
 
PPT
JMS Introduction
Alex Su
 
PPT
Java Server Faces (JSF) - advanced
BG Java EE Course
 
PDF
The Modern Java Web Developer Bootcamp - Devoxx 2013
Matt Raible
 
Lecture 7 Web Services JAX-WS & JAX-RS
Fahad Golra
 
Lecture 10 - Java Server Faces (JSF)
Fahad Golra
 
Lecture 8 Enterprise Java Beans (EJB)
Fahad Golra
 
Tutorial 4 - Basics of Digital Photography
Fahad Golra
 
Lecture 3: Servlets - Session Management
Fahad Golra
 
Enterprise Java Beans - EJB
Peter R. Egli
 
Tutorial 3 - Basics of Digital Photography
Fahad Golra
 
Tutorial 1 - Basics of Digital Photography
Fahad Golra
 
Tutorial 2 - Basics of Digital Photography
Fahad Golra
 
TNAPS 3 Installation
tncor
 
Ejb in java. part 1.
Asya Dudnik
 
2012-12-01 03 Битва ORM: Hibernate vs MyBatis. Давайте жить дружно!
Омские ИТ-субботники
 
Lazy vs. Eager Loading Strategies in JPA 2.1
Patrycja Wegrzynowicz
 
Apache Lucene + Hibernate = Hibernate Search
Vitebsk Miniq
 
Interoperable Web Services with JAX-WS
Carol McDonald
 
JPA - Java Persistence API
Thomas Wöhlke
 
Hibernate ORM: Tips, Tricks, and Performance Techniques
Brett Meyer
 
JMS Introduction
Alex Su
 
Java Server Faces (JSF) - advanced
BG Java EE Course
 
The Modern Java Web Developer Bootcamp - Devoxx 2013
Matt Raible
 
Ad

Similar to Lecture 9 - Java Persistence, JPA 2 (20)

PPT
test for jpa spring boot persistence hehe
AdePutraNurcholikSan
 
PDF
2014 Pre-MSc-IS-3 Persistence Layer
andreasmartin
 
PDF
Persistence
Abdalla Mahmoud
 
PDF
Java Persistence API
Ilio Catallo
 
PDF
Java persistence api 2.1
Rakesh K. Cherukuri
 
PPTX
Introduction to JPA (JPA version 2.0)
ejlp12
 
PDF
Using the latest Java Persistence API 2 Features - Tech Days 2010 India
Arun Gupta
 
PPT
Java persistence api
Luis Goldster
 
PDF
Using the latest Java Persistence API 2.0 features
Arun Gupta
 
PPTX
Jakarta Persistence (JPA) - Web Technologies
ssuser0562f1
 
PPT
Jpa basics
Balaji Vericharla
 
PPT
Al rihieli persistence
Jhonny Villarroel
 
PPTX
Jpa 2.1 Application Development
ThirupathiReddy Vajjala
 
PPT
Java Persistence API (JPA) Step By Step
Guo Albert
 
PPT
Java Persistence API (JPA) - A Brief Overview
Craig Dickson
 
PPTX
Jpa 2.0 in java ee 6 part ii
Lars Lemos
 
PPT
Jpa
Manav Prasad
 
PDF
Java Persistence API 2.0: An Overview
Sanjeeb Sahoo
 
ODP
Working with jpa
Ondrej Mihályi
 
PDF
Jpa
vantinhkhuc
 
test for jpa spring boot persistence hehe
AdePutraNurcholikSan
 
2014 Pre-MSc-IS-3 Persistence Layer
andreasmartin
 
Persistence
Abdalla Mahmoud
 
Java Persistence API
Ilio Catallo
 
Java persistence api 2.1
Rakesh K. Cherukuri
 
Introduction to JPA (JPA version 2.0)
ejlp12
 
Using the latest Java Persistence API 2 Features - Tech Days 2010 India
Arun Gupta
 
Java persistence api
Luis Goldster
 
Using the latest Java Persistence API 2.0 features
Arun Gupta
 
Jakarta Persistence (JPA) - Web Technologies
ssuser0562f1
 
Jpa basics
Balaji Vericharla
 
Al rihieli persistence
Jhonny Villarroel
 
Jpa 2.1 Application Development
ThirupathiReddy Vajjala
 
Java Persistence API (JPA) Step By Step
Guo Albert
 
Java Persistence API (JPA) - A Brief Overview
Craig Dickson
 
Jpa 2.0 in java ee 6 part ii
Lars Lemos
 
Java Persistence API 2.0: An Overview
Sanjeeb Sahoo
 
Working with jpa
Ondrej Mihályi
 
Ad

More from Fahad Golra (6)

PDF
Seance 4- Programmation en langage C
Fahad Golra
 
PDF
Seance 3- Programmation en langage C
Fahad Golra
 
PDF
Seance 2 - Programmation en langage C
Fahad Golra
 
PDF
Seance 1 - Programmation en langage C
Fahad Golra
 
PPTX
Deviation Detection in Process Enactment
Fahad Golra
 
PPTX
Meta l metacase tools & possibilities
Fahad Golra
 
Seance 4- Programmation en langage C
Fahad Golra
 
Seance 3- Programmation en langage C
Fahad Golra
 
Seance 2 - Programmation en langage C
Fahad Golra
 
Seance 1 - Programmation en langage C
Fahad Golra
 
Deviation Detection in Process Enactment
Fahad Golra
 
Meta l metacase tools & possibilities
Fahad Golra
 

Recently uploaded (20)

PPTX
Revolutionizing Code Modernization with AI
KrzysztofKkol1
 
PPTX
Comprehensive Guide: Shoviv Exchange to Office 365 Migration Tool 2025
Shoviv Software
 
PPTX
How Apagen Empowered an EPC Company with Engineering ERP Software
SatishKumar2651
 
PDF
iTop VPN With Crack Lifetime Activation Key-CODE
utfefguu
 
PPTX
Feb 2021 Cohesity first pitch presentation.pptx
enginsayin1
 
PDF
유니티에서 Burst Compiler+ThreadedJobs+SIMD 적용사례
Seongdae Kim
 
PPTX
Fundamentals_of_Microservices_Architecture.pptx
MuhammadUzair504018
 
PPTX
A Complete Guide to Salesforce SMS Integrations Build Scalable Messaging With...
360 SMS APP
 
PPTX
An Introduction to ZAP by Checkmarx - Official Version
Simon Bennetts
 
PPTX
MiniTool Power Data Recovery Full Crack Latest 2025
muhammadgurbazkhan
 
PDF
Alexander Marshalov - How to use AI Assistants with your Monitoring system Q2...
VictoriaMetrics
 
PPTX
Tally_Basic_Operations_Presentation.pptx
AditiBansal54083
 
PPTX
Agentic Automation Journey Session 1/5: Context Grounding and Autopilot for E...
klpathrudu
 
PDF
MiniTool Partition Wizard 12.8 Crack License Key LATEST
hashhshs786
 
PDF
Understanding the Need for Systemic Change in Open Source Through Intersectio...
Imma Valls Bernaus
 
PPTX
3uTools Full Crack Free Version Download [Latest] 2025
muhammadgurbazkhan
 
PPTX
Writing Better Code - Helping Developers make Decisions.pptx
Lorraine Steyn
 
PDF
Capcut Pro Crack For PC Latest Version {Fully Unlocked} 2025
hashhshs786
 
PPTX
MailsDaddy Outlook OST to PST converter.pptx
abhishekdutt366
 
PDF
Thread In Android-Mastering Concurrency for Responsive Apps.pdf
Nabin Dhakal
 
Revolutionizing Code Modernization with AI
KrzysztofKkol1
 
Comprehensive Guide: Shoviv Exchange to Office 365 Migration Tool 2025
Shoviv Software
 
How Apagen Empowered an EPC Company with Engineering ERP Software
SatishKumar2651
 
iTop VPN With Crack Lifetime Activation Key-CODE
utfefguu
 
Feb 2021 Cohesity first pitch presentation.pptx
enginsayin1
 
유니티에서 Burst Compiler+ThreadedJobs+SIMD 적용사례
Seongdae Kim
 
Fundamentals_of_Microservices_Architecture.pptx
MuhammadUzair504018
 
A Complete Guide to Salesforce SMS Integrations Build Scalable Messaging With...
360 SMS APP
 
An Introduction to ZAP by Checkmarx - Official Version
Simon Bennetts
 
MiniTool Power Data Recovery Full Crack Latest 2025
muhammadgurbazkhan
 
Alexander Marshalov - How to use AI Assistants with your Monitoring system Q2...
VictoriaMetrics
 
Tally_Basic_Operations_Presentation.pptx
AditiBansal54083
 
Agentic Automation Journey Session 1/5: Context Grounding and Autopilot for E...
klpathrudu
 
MiniTool Partition Wizard 12.8 Crack License Key LATEST
hashhshs786
 
Understanding the Need for Systemic Change in Open Source Through Intersectio...
Imma Valls Bernaus
 
3uTools Full Crack Free Version Download [Latest] 2025
muhammadgurbazkhan
 
Writing Better Code - Helping Developers make Decisions.pptx
Lorraine Steyn
 
Capcut Pro Crack For PC Latest Version {Fully Unlocked} 2025
hashhshs786
 
MailsDaddy Outlook OST to PST converter.pptx
abhishekdutt366
 
Thread In Android-Mastering Concurrency for Responsive Apps.pdf
Nabin Dhakal
 

Lecture 9 - Java Persistence, JPA 2

  • 1. Java Persistence, JPA 2 Fahad R. Golra ECE Paris Ecole d'Ingénieurs - FRANCE
  • 2. Lecture 8 - Java Persistence, JPA 2 • Introduction to Persistence • Entity Beans • Life cycle of Entity Beans • Associations • Entity Beans: Query Language 2 JEE - Java Persistence, JPA 2.x
  • 3. Introduction to Entity Beans • Entity Bean • Persistent objects stored in the database • Persistence • by serialization • by object - relational database mapping • Serialization • Saving the state of an object in the form of bytes • An object can be reconstructed once serialized • No complex queries, hard to maintain 3 JEE - Java Persistence, JPA 2.x
  • 4. Persistence by mapping objects to relational databases • State of the object is store in a database • For example: a book object has the attributes names and isbn. We map them to a table which has two columns: name and isbn. • Every object is decomposed into multiple variables, and their values are then stored in one or more tables. • Allows complex queries • SQL is hard to test/debug 4 JEE - Java Persistence, JPA 2.x
  • 5. Persistence by mapping objects to relational databases 5
  • 6. Object Databases • Object databases (also known as object-oriented database management systems) can store the objects directly to databases. • No mapping !!! • Object Query Language (OQL) can be used to manipulate objects • Easy to use, but not scalable. 6 JEE - Java Persistence, JPA 2.x
  • 7. Persistence through JPA 2 • JPA 2 proposes a standard model of persistence through the use of Entity Beans • Tools that ensure this persistence are integrated with the application servers and must be compatible to JPA 2 standard • e.g. Toplink, Hibernate, EclipseLink • Java EE permits the use of dependency injection through annotations on all the layers. 7 JEE - Java Persistence, JPA 2.x
  • 8. What is an Entity Bean? • An object that is mapped to a database • It uses the persistence mechanisms • It serves to represent the data placed in the database as objects • An object = one or more rows in one or more tables in the database • Example • A student entity is represented by a row of data in student table of a database 8 JEE - Java Persistence, JPA 2.x
  • 9. Why an Entity Bean? • Easy to manipulate by programs • Instance of Account entity • A compact view of grouped data in an object • Account object gives access to all public variables • Associating methods to manipulate the data • methods can be written to add behavior to Account • The data in the database will be updated automatically • Instance of an entity bean is a view in memory of physical data 9 JEE - Java Persistence, JPA 2.x
  • 10. Entity Bean • Entity Bean is a POJO with attributes, getters & setters. • These attributes are mapped to database tables • We use annotations to define the mapping to attributes • Primary Key, is a serializable object • Attributes of annotations to customize the mapping 10 JEE - Java Persistence, JPA 2.x
  • 11. Persistent Fields and Properties • Java primitive types • java.lang.String • Other serializable types, including: • Wrappers of Java primitive types • java.math.BigInteger • java.math.BigDecimal • java.util.Date • java.util.Calendar • java.sql.Date • java.sql.Time 11 • java.sql.TimeStamp • User-defined serializable types • byte[] • Byte[] • char[] • Character[] • Enumerated types • Other entities and/or collections of entities • Embeddable classes
  • 12. Example: Entity Bean (Book) @Entity public class Book implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue private Long id; @Column(nullable = false) private String title; private Float price; @Column(length = 2000) private String description; private String isbn; private Integer nbOfPage; private Boolean illustrations; // Constructors, getters, setters } 12
  • 13. Example Entity Bean: Book 13 JEE - Java Persistence, JPA 2.x
  • 14. Entity Manager • We manipulate the data in the database with the help of Entity Beans and a Entity Manager • Entity Manager is responsible of access the disks, caches, etc. • Entity Manager controls when and how we can access the database. • It generates the SQL. 14 JEE - Java Persistence, JPA 2.x
  • 15. Example: Client (Inserting a Book) public class BookHandler { public static void main(String[] args) { Book book = new Book(); book.setTitle("The Hitchhiker's Guide to the Galaxy"); book.setPrice(12.5F); book.setDescription("Science fiction comedy book”); // set other fields as well . . . // Get a pointer to entity manager. We don't need to do this in web app! EntityManagerFactory emf = Persistence .createEntityManagerFactory("chapter02PU"); EntityManager em = emf.createEntityManager(); // Persisting the object in a transaction EntityTransaction tx = em.getTransaction(); tx.begin(); em.persist(book); tx.commit(); em.close(); emf.close(); }} 15
  • 16. Session Bean as a Client • In such a case • Dependency injection can be used • Transactions are started by default @Stateless @LocalBean public class MySessionBean { EntityManager em; public Employee createEmployee(int id, String name, long salary) { Employee emp = new Employee(id); emp.setName(name); ….. em.persist(emp); return emp; } } 16 JEE - Java Persistence, JPA 2.x
  • 17. Session Bean as a Client 17 @Stateless public class BookBean { @PersistenceContext(unitName = "bookLib") private EntityManager em; public void createBook() { Book book = new Book(); book.setId(1234L); book.setTitle("The Alpha Book"); book.setPrice(13.5F); book.setDescription("Description of my book"); book.setIsbn("1-465-65465"); book.setNbOfPage(230); book.setIllustrations(false); em.persist(book); book = em.find(Book.class, 1234L); System.out.println(book); }}
  • 18. Why use session beans? • They are used to implement the business logic • A session bean can be used to implement Data Access Object (DAO) • DAO offers the functions of creation, searching, modification and deletion of entity beans. • Session beans can also be used to implement composite services. 18 JEE - Java Persistence, JPA 2.x
  • 19. Other Annotations @Entity public class Book implements Serializable { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @Column(name = "book_title", nullable = false, updatable = false) private String title; private Float price; @Column(length = 2000) private String description; private String isbn; @Column(name = "nb_of_page", nullable = false) private Integer nbOfPage; @Basic(fetch = FetchType.LAZY) @Lob private Boolean illustrations; // Constructors, getters, setters } 19
  • 20. Other Annotations • @Column • allows the preferences for columns • Attributes: name, unique, nullable, insertable, updatable, length, …. • @Generated Value • indicates the strategy for the automatic generation of primary keys • It depends on the database being used, so automatic is recommended 20 JEE - Java Persistence, JPA 2.x
  • 21. Other Annotations • @Lob • indicates “large object” for a BLOB • Often used with @Basic(fetch=FetchType.LAZY) for indicating that we want this attribute to be loaded only when a get is used on it. • There are many other annotations. • Java EE 7 specification can be consulted for it. 21 JEE - Java Persistence, JPA 2.x
  • 22. Example: Persistence.xml <?xml version="1.0" encoding="UTF-8"?> <persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd" version="1.0"> <persistence-unit name="JPA_first"> <provider>oracle.toplink.essentials.PersistenceProvider</provider> <class>com.ece.jee.entities.Client</class> <properties> <property name="toplink.jdbc.driver" value="com.mysql.jdbc.Driver" / > <property name="toplink.jdbc.url" value="jdbc:mysql://localhost: 3306/ece_db" /> <property name="toplink.jdbc.user" value="root" /> <property name="toplink.jdbc.password" value="secret" /> <property name="toplink.target-database" value="MySQL4" /> <property name="toplink.ddl-generation" value="drop-and-create- tables" /> <property name="toplink.ddl-generation.output-mode" value="both" /> <property name="toplink.logging.level" value="FINE" /> </properties> </persistence-unit> </persistence> 22
  • 23. Persistence Context • A persistence context is a set of entity instances in which for every persistent entity identity there is a unique entity instance. • The entity instances and their lifecycle are managed within the persistence context. • The EntityManager API is used to create and remove persistent entity instances, to find entities by their primary keys, and to query over entities. 23 JEE - Java Persistence, JPA 2.x
  • 24. Life cycle of Entity Bean 24 JEE - Java Persistence, JPA 2.x
  • 25. Life cycle of Entity Bean • New: The bean exists in the memory but is not mapped to DB yet. It is not yet mapped to persistence context (via entity manager) • Managed: The bean is mapped to the DB. The changes effect the data in DB. • Detached: The bean is not mapped to the persistence context anymore. • Removed: The bean is still mapped to the persistence context and the DB, but it is programmed to be deleted. 25 JEE - Java Persistence, JPA 2.x
  • 26. Life cycle of Entity Bean • remove(): To delete the data • set(), get(): If the bean is in managed state, these methods (of the entity bean) are used to access or modify the data. • persist(): To create the data. The bean goes to managed state. • merge(): To take a bean from detached state to a managed state. 26 JEE - Java Persistence, JPA 2.x
  • 27. Entity Manager example methods public Account openAccount(String ownerName) { Account account = new Account(); account.ownerNamer = ownerName; em.persist(account); // attach the bean & persist return account; // copy is detached } public void update(Account detachedAccount) { Account managedAccount = em.merge(detachedAccount); } public void delete(Account detachedAccount) { Account managedAccount = em.merge(detachedAccount); em.remove(managedAccount); } public void findAccount(int id) { return em.find(Account.class, Integer.valueOf(id)); } 27
  • 28. Entity Manager (other principal methods) Object find(Class cl, Object key) : • Find an EntityBean by its id boolean contains(Object entity) : • True if the entity is attached to the EntityManager Query createQuery(String sqlString) : • Creating a query in EJB-QL Query createNamedQuery(String name) : • Creating a named query Query createNativeQuery(String sqlQuery) : • Creating an SQL query void refresh(Object entity) : • Recharging the bean from the DB 28 JEE - Java Persistence, JPA 2.x
  • 29. Using composite columns • Fields of two classes into one table @Embeddable public class Address { private String street; private int postalCode; } @Entity public class User { private String name; @Embedded private Address address; } 29
  • 30. Composite Primary Key • Instead of using @Embedded we use @EmbeddedId for composite primary keys @Embeddable public class CompositeId { private String name; private String email; } @Entity public class Dependent { @EmbeddedId CompositeId id; @ManyToOne Employee emp; } 30
  • 31. Associations • Cardinality • 1 - 1 (one to one): one employee has one address • 1 - n (one to many): one employee has multiple addresses • n - 1 (many to one): multiple employees have one address • n - n (many to many): multiple employees have multiple addresses • Direction (navigability) • Unidirectional: • we can go from bean A to bean B only • Bi-directional: • we can go from bean A to bean B & vice-versa 31 JEE - Java Persistence, JPA 2.x
  • 32. Unidirectional: OneToOne • Employee entity -> ︎Employee table • Address entity -> ︎Address table with address_Id as PK • Employee table owns a foreign key to Address, address @Entity public class Employee { private Address address; @OneToOne public Address getAddress() { return address; } public void setAddress(Address ad) { this.address = ad; } } 32 @Entity public class Address { … } Employee Address 1 1 adress
  • 33. Unidirectional: ManyToOne • Employee entity -> ︎Employee table • Address entity -> ︎Address table with address_Id as PK • Employee table owns a foreign key to Address, address @Entity public class Employee { private Address address; @ManyToOne public Address getAddress() { return address; } public void setAddress(Address ad) { this.address = ad; } } 33 @Entity public class Address { … } Employee Address 0..* 1 adress
  • 34. Unidirectional: OneToMany • Employee entity -> ︎Employee table • Address entity -> ︎Address table with address_Id as PK • Creation of a join table Employee_Address with two columns (i.e. Employee_Pkemployee & Address_PKAddress, each column represents a PK to each table @Entity public class Employee { private Collection<Address> addresses; @OneToMany public Collection<Address> getAddresses() { return addresses; } public void setAddresses(Collection<Address> addresses) { this.addresses = addresses; } }34 @Entity public class Address { … } Employee Address 1 0..* adresses
  • 35. Unidirectional: ManyToMany • Employee entity -> ︎Employee table • Address entity -> ︎Address table with address_Id as PK • Creation of a join table Employee_Address with two columns (i.e. Employee_Pkemployee & Address_PKAddress, each column represents a PK to each table @Entity public class Employee { private Collection<Address> addresses; @ManyToMany public Collection<Address> getAddresses() { return addresses; } public void setAddresses(Collection<Address> addresses) { this.addresses = addresses; } } 35 @Entity public class Address { … } Employee Address 0..* 0..* adresses
  • 36. Bi-directional: OneToOne • Employee entity -> ︎Employee table • Cashier entity -> ︎Cashier table with myCashier_Id as PK • Employee table owns a foreign key to Cashier, myCashier (note: Cashier will not have a foreign key to Employee) 36 @Entity public class Cashier { private Employee myEmployee; @OneToOne(mappedBy = "myCashier") public Employee getMyEmployee() { return myEmployee; } public void setMyEmploye(Employee e) { this.myEmployee = e; } } @Entity public class Employee { private Cashier myCashier; @OneToOne public Cashier getMyCashier() { return myCashier; } public void setMyCashier(Cashier c) { this.myCashier = c; } } Employee Cashier 1 1 myCashiermyEmployee
  • 37. Bi-directional: ManyToOne/OneToMany • Employee entity -> ︎Employee table • Cashier entity -> ︎Cashier table with myCashier_Id as PK • Employee table owns a foreign key to Cashier, myCashier (note: Cashier will not have a foreign key to Employee) 37 @Entity public class Cashier { private Collection<Employee> myEmployees; @OneToMany(mappedBy = "myCashier") public Collection<Employee> getMyEmployees() { return myEmployees; } public void setMyEmployees(Collection<Employee> e) { this.myEmployees = e; } } @Entity public class Employee { private Cashier myCashier; @ManyToOne public Cashier getMyCashier() { return myCashier; } public void setMyCashier(Cashier c) { this.myCashier = c; } } Employee Cashier 0..* 1 myCashiermyEmployees
  • 38. Bi-directional: ManyToMany • Employee entity -> ︎Employee table • Cashier entity -> ︎Cashier table • Creation of a join table Project_Employee with two columns (i.e. myProjects_PKProject & myEmployees_PkEmployee, each column represents a PK to each table 38 @Entity public class Employee { private Collection<Project> myProjects; @ManyToMany(mappedBy = "myEmployees") public Collection<Project> getMyProjets() { return myProjects; } public void setMyProjets(Collection<Project> p) { this.myProjects = p; } } @Entity public class Project { Collection<Employee> myEmployees; @ManyToMany public Collection<Employee> getMesEmployees() { return myEmployees; } public void setMesEmployes(Collection<Employee> e) { this.myEmployees = e; } } Project Employee 0..* 0..* myEmployeesmyProjects
  • 39. Entity Bean Inheritance • Entities support inheritance and polymorphism • Entities may be concrete or abstract @Entity public abstract class Person { @Id protected String name; … } @Entity public class Employee extends Person { protected float salary; … } 39 JEE - Java Persistence, JPA 2.x
  • 40. Inheritance Strategies • One Table by classes hierarchy (Default) : @Inheritance(strategy=SINGLE_TABLE) • Implemented in most tooling solutions • Good support of polymorphism • Columns proper to sub-classes set at null • One Table by concrete class: @Inheritance(strategy=TABLE_PER_CLASS) • Some issues remain regarding polymorphism • Join Strategy: • @Inheritance(strategy=JOINED) • a join between the concrete class and the super class tables • Good support of polymorphism • Not always implemented • Join operation can be costly 40 JEE - Java Persistence, JPA 2.x
  • 41. Entity Bean Inheritance • An Entity can inherit a non-entity class and vice-versa • MappedSuperClasses are not accessible to EntityManager • Not considered as Entity (no table in DB) @MappedSuperclass public abstract class Person { protected Date dob; } @Entity public class Employee extends Person { @Id protected int id; protected String name; } 41 JEE - Java Persistence, JPA 2.x
  • 42. Entity Bean Compliments • Fetch: option for loading the graph of objects • FetchType.EAGER : loads all the tree (required if Serializable) ︎ • FetchType.LAZY : only on demand (unusable with Serializable) • Cascade: transitivity of operations over the beans • CascadeType.ALL: every operation is propagated • CascadeType.MERGE: in case of a merge • CascadeType.PERSIST: When film Entity becomes persistent, then List<Cinema> too • CascadeType.REFRESH: loading from the DB • ︎CascadeType.REMOVE: delete in cascade 42 JEE - Java Persistence, JPA 2.x
  • 43. Entity Beans: Query Language • parameters indicated by :param-name • Request in Query object • Result from Query object • getResultList() • getSingleResult() 43 JEE - Java Persistence, JPA 2.x
  • 44. Entity Beans: Named Query • Named query can be attached to the Entity Bean 44 JEE - Java Persistence, JPA 2.x
  • 45. Entity Beans: Native Query • SQL queries can be used using • createNativeQuery(String sqlString) • createNativeQuery(String sqlString, Class resultClass) 45 JEE - Java Persistence, JPA 2.x
  • 46. Entity Beans: Life cycle interceptors • Interception of state changes • Around the creation (em.persist) : ︎ • @PrePersist • @PostPersist • At loading time from DB (em.find, Query.getResultList) • @PostLoad • Around updates (modification of a field, em.merge) ︎ • @PreUpdate • @PostUpdate • Around a remove action (em.remove) ︎ • @PreRemove • @PostRemove 46
  • 47. References • Some of the slide contents are take from the slides of • Reda Bendraou, UPMC • Michel Buffa, UNSA 47 JEE - Java Persistence, JPA 2.x
  • 48. 48 JEE - Java Persistence, JPA 2.x