1
Module 8The Java Persistence API
Java
Per
sist
ence
AP
I8
220 Ω Omega ΩDeveloping Applications for Java EE Platform
Describe the role of the Java Persistence API (JPA) in a Java EE application
Describe the basics of Object Relational Mapping
Describe the elements and environment of an entityComponent
Describe the life cycle and operational characteristics of entity components
Objectives
2
Java
Per
sist
ence
AP
I8
221 Ω Omega ΩDeveloping Applications for Java EE Platform
What is data persistence?
What is the Java persistence specification?
How does the Java Persistence API relate to Java EEapplication servers?
What are the key features of the persistence modelspecified in the Java Persistence API?
Examining Java PersistenceJa
va P
ersi
sten
ce A
PI8
222 Ω Omega ΩDeveloping Applications for Java EE Platform
Static Relationship Mapping - Data Tier
Elements
3
Java
Per
sist
ence
AP
I8
223 Ω Omega ΩDeveloping Applications for Java EE Platform
Static Relationship Mapping - Object Tier
Elements
Java
Per
sist
ence
AP
I8
224 Ω Omega ΩDeveloping Applications for Java EE Platform
Dynamic Relationship - Object/Data Tier Data
Synchronization
With entities, the data synchronization is maintained by the persistence provider.
4
Java
Per
sist
ence
AP
I8
225 Ω Omega ΩDeveloping Applications for Java EE Platform
The Java Persistence API
The Java Persistence API: Replaces EJB 2.1 Entity Beans with non-EJB entity classes Is a standard API for specifying Object-to-Relationalmapping information Can be used with or without a Java EE Application Server Container-Managed Persistence Application-Managed Persistence
Java
Per
sist
ence
AP
I8
226 Ω Omega ΩDeveloping Applications for Java EE Platform
Object Relational Mapping
Object Relational Mapping (ORM) software: Provides an object-oriented view of the database Examples include Oracle’s Toplink and Hibernate
5
Java
Per
sist
ence
AP
I8
227 Ω Omega ΩDeveloping Applications for Java EE Platform
Normalized Data MappingJa
va P
ersi
sten
ce A
PI8
228 Ω Omega ΩDeveloping Applications for Java EE Platform
Use of an Entity Component Across a Set of
Database Tables
6
Java
Per
sist
ence
AP
I8
229 Ω Omega ΩDeveloping Applications for Java EE Platform
Entity Class Requirements
Entity classes are coded as standard Java classes with the following requirements: javax.persistence.Entity annotation on the class or declared as an Entity in a deployment descriptor Must be a public class No-argument constructor with public or protected access Open to extension, in other word they are not final classes Implement Serializable if they are to be returned by remote session beans Top-level class, entity classes cannot be inner classes
Java
Per
sist
ence
AP
I8
230 Ω Omega ΩDeveloping Applications for Java EE Platform
Entity Class Exampleimport java.io.Serializable;import javax.persistence.*;
@Entity @Table( name = "TABLE1")public class MyEntity implements Serializable
@Id @Column( name = "ID") private int id;@Column( name = "MSG") private String message;
protected MyEntity() public MyEntity(int id, String message)
this.id = id;this.message = message;
public int getId() return id; public String getMessage() return message; public void setMessage(String message)
this.message = message;
7
Java
Per
sist
ence
AP
I8
231 Ω Omega ΩDeveloping Applications for Java EE Platform
Persistent Fields as Opposed to Persistent
Properties
Entity classes have their state synchronized with a database. The state of an entity class is obtained from either its variables (fields) or its accessor methods (properties). Field-based or property-based access: Determined by the placement of annotations Cannot have both field-based and property-based access
Java
Per
sist
ence
AP
I8
232 Ω Omega ΩDeveloping Applications for Java EE Platform
Persistent Fields
When using persistent fields, the persistence provider retrieves an object’s state by reading its variables. Persistent fields cannot be public Should not be read by clients directly Unless annotated with @Transient or modified with the
transient keyword, all variables are persisted regardless of whether they have a @Column annotation.
@Id @Column(name = "ID") private int id;@Column(name = "MSG") private String message;
public int getId() return id; public String getMessage() return message; public void setMessage(String message) this.message=message;
8
Java
Per
sist
ence
AP
I8
233 Ω Omega ΩDeveloping Applications for Java EE Platform
Persistent Properties
When using persistent properties, the persistence provider retrieves an object’s state by calling its accessor methods. Methods must be public or protected Methods follow the JavaBeans naming convention Persistence annotations can only be on getter methods
private int id;private String message;
@Id @Column(name = "ID") public int getId() return id; public void setId(int id) this.id = id; @Column(name = "MSG") public String getMessage() return message; public void setMessage(String message) this.message=message;
Java
Per
sist
ence
AP
I8
234 Ω Omega ΩDeveloping Applications for Java EE Platform
Persistence Data Types
Persistence fields or properties can be of the following data types Java primitive types Java wrappers, such as java.lang.Integer java.lang.String byte[] and Byte[] char[] and Character[] Any serializable types including but not limited to: java.util.Date java.sql.Date java.sql.TimeStamp
9
Java
Per
sist
ence
AP
I8
235 Ω Omega ΩDeveloping Applications for Java EE Platform
The Concept of a Primary Key
An entity component distinguishes itself and the data it represents from other entities using a primary key. A primary key gives an entity instance its persistent identity. They are typically a string or an integer but can also be custom classes that correspond to several database table columns. Every entity class must have a primary key. Can be auto incrementing.
@Id @GeneratedValue( strategy = GenerationType.IDENTITY)@Column( name = "ID", nullable = false)private int id;
Java
Per
sist
ence
AP
I8
236 Ω Omega ΩDeveloping Applications for Java EE Platform
Entity Component Primary Key Association
10
Java
Per
sist
ence
AP
I8
237 Ω Omega ΩDeveloping Applications for Java EE Platform
Persistence Units
A persistence unit is a collection of entity classes stored in a EJB-Jar, WAR, or JAR archive along with a persistence.xml file. A persistence unit: Defines what entity classes will be controlled by an entity manager Is limited to a single DataSource
Java
Per
sist
ence
AP
I8
238 Ω Omega ΩDeveloping Applications for Java EE Platform
The persistence.xml file
The persistence.xml file: Configures which classes make up a persistence unit Defines the base of a persistence unit Specifies the DataSource used
<?xml version="1.0" encoding="UTF-8"?><persistence version="1.0”
xmlns="http://java.sun.com/xml/ns/persistence"><persistence-unit name="BrokerTool-ejb" transaction-type="JTA">
<jta-data-source>StockMarket</jta-data-source><jar-file>BrokerLibrary.jar</jar-file>
<properties/></persistence-unit>
</persistence>
11
Java
Per
sist
ence
AP
I8
239 Ω Omega ΩDeveloping Applications for Java EE Platform
The Persistence Context
A persistence context can be thought of as a working copy of a persistence unit. Several persistence contexts using the same persistence unit can be active at the same time. A persistencecontext: Typically lasts the duration of a transaction Limits entity instances to a single instance per persistentidentity Has a management API, known as the entity manager
Java
Per
sist
ence
AP
I8
240 Ω Omega ΩDeveloping Applications for Java EE Platform
The Entity Manager
An Entity Manager provides methods to control events of a persistence context and the life cycle of entity instances in a persistence context. An Entity Manager: Provides operations, such as flush() , find() , andcreateQuery() , to control a persistence context Replaces some of the functionality of home interfaces in EJB 2.1 Entity Beans Obtained using dependency injection in managed classes.
@PersistenceContext private EntityManager em;
12
Java
Per
sist
ence
AP
I8
241 Ω Omega ΩDeveloping Applications for Java EE Platform
Entity Instance Management
@Remote @Statelesspublic class BrokerModelImpl implements BrokerModel
@PersistenceContext private EntityManager em;public Stock getStock(String symbol) throws BrokerException
Stock stock = em. find(Stock.class, symbol);if (stock != null)
return stock; else
throw new BrokerException("Stock : "+symbol+" not found");
public void addStock(Stock stock) throws BrokerException
try em.persist(stock);
catch(EntityExistsException exe) throw new BrokerException("Duplicate Stock : " +
Java
Per
sist
ence
AP
I8
242 Ω Omega ΩDeveloping Applications for Java EE Platform
stock.getSymbol());
public void updateStock(Stock stock) throws BrokerException
Stock s = em. find(Stock.class, stock.getSymbol());if (s == null)
throw new BrokerException("Stock : " + stock.getSymbol() " not found");
else em.merge(stock);
public void deleteStock(Stock stock) throws BrokerException
String id = stock.getSymbol();stock = em. find(Stock.class, id);if (stock == null)
throw new BrokerException("Stock : " + stock.getSymbol() +" not found");
else em.remove(stock);
13
Java
Per
sist
ence
AP
I8
243 Ω Omega ΩDeveloping Applications for Java EE Platform
Entity Instance Life Cycle and Entity Manager
Methods
Java
Per
sist
ence
AP
I8
244 Ω Omega ΩDeveloping Applications for Java EE Platform
Entity Bean States
Entity beans have a transitional life cycle. An entity can exist in one of four states: New – The entity instance is newly created and not connected to a persistence context. Managed – The entity instance is connected to a persistence context and has a unique entity identity. Only one managed instance of a identity can exist in a persistence context. Detached – The entity instance is not connected to a persistence context. Removed – The entity instance is scheduled for deletion.
14
Java
Per
sist
ence
AP
I8
245 Ω Omega ΩDeveloping Applications for Java EE Platform
Entity Manager MethodsJa
va P
ersi
sten
ce A
PI8
246 Ω Omega ΩDeveloping Applications for Java EE Platform
Entity Life Cycle Callback Annotations
An entity instance can be notified before or after life- cycle changes using specially annotated methods in the entity class. Life-cycle annontations: @PrePersist @PostPersist @PreRemove @PostRemove @PreUpdate @PostUpdate @PostLoad
15
Java
Per
sist
ence
AP
I8
247 Ω Omega ΩDeveloping Applications for Java EE Platform
Deploying Entity Classes
To deploy entity classes, you must create a persistence unit. A persistence unit includes entity classes and a persistence.xml configuration file. The persistence unit exists inside of Java EE modules, such as EJB-JAR files and WAR files. Within these Java EE modules, you can have persistence units that include library jars.
Java
Per
sist
ence
AP
I8
248 Ω Omega ΩDeveloping Applications for Java EE Platform
Creating a Persistence Unit Using Default
SettingsA persistence unit attempts to include all entity classes in the same EJB module as the persistence.xml file.
16
Java
Per
sist
ence
AP
I8
249 Ω Omega ΩDeveloping Applications for Java EE Platform
Examining a Persistence Unit Using Non-
Default Settings
A persistence unit can be made to include library jar files it would not normally include.
Java
Per
sist
ence
AP
I8
250 Ω Omega ΩDeveloping Applications for Java EE Platform
A Native Query Example
Native queries are easier to use because they do not require that you learn the Java Persistence query language. However, native queries should not be used extensively because they are non-portable.
Query query = em.createNativeQuery("SELECT * FROM Customer", Customer.class);List customers = query.getResultList();
Query query = em.createNativeQuery("SELECT * FROM SHARES WHERE SSN = '" + customerId + "'", CustomerShare.class);List shares = query.getResultList();