Professional Documents
Culture Documents
Simplifying Persistence
1
Agenda
• Java Persistence Requirements
• JPA Programming Model
• Persistence Context & Entity Manager
• Transaction
• O/R Mapping
• Entity Relationships
• Entity Inheritance Strategy
Java Persistence
Requirements
Java Persistence Requirements
• Simplification of the persistence model
> Elimination of deployment descriptor
> Most configuration is defaulted – configure by exception only
(configure only to override default)
• POJO based programming/persistence model
> Simple Java classes – not EJB components, only 1 file instead of 3
> Entities usable outside the container
> No need for Data Transfer Objects
> Facilitates testability outside of the containers
• Standardized object/relational mapping
> Standardized annotations @ and XML configuration files
> xml for mapping is optional
• Domain modelling through inheritance and polymorphism
• Extensive querying capabilities
Common Java Persistence Between
J2SE and J2EE Environments
public Customer() {}
…
}
Entity Identity
• Every entity has a persistence identity
> Maps to primary key in database
• Identity can be application or database generated
• Can correspond to simple type
> @Id—single field/property in entity class
> @GeneratedValue—value can be generated automatically
using various strategies (SEQUENCE, TABLE, IDENTITY,
AUTO)
• Can correspond to user-defined class
> @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
Types of Identity
• Simple
> @Id – single field/property in entity class
> @GeneratedValue
@Id @GeneratedValue(strategy=SEQUENCE)
private int id;
• User defined:
> @EmbeddedId – single field/property in entity class
@EmbeddedId Class must be
@Embeddable
private EmployeePK pk;
> @IdClass – corresponds to multiple id field in entity class
@Entity
@IdClass(EmployeePK.class)
public class Employee {
@Id private String empName;
@Id private int dept;
JPA
Programming Model
Java Persistence Programming Model
• Entity is a POJO (no need to implement EntityBean)
• Use of Annotation to denote a POJO as an entity (instead
of deployment descriptor)
// @Entity is an annotation
// It annotates Employee POJO class to be Entity
@Entity
public class Employee {
// Persistent/transient fields
// Property accessor methods
// Persistence logic methods
}
Persistence Entity Example
@Entity Annotated as “Entity”
public class Customer {
private Long id;
private String name;
private Address address;
private Collection<Order> orders = new HashSet();
public Customer() {}
@Id denotes primary key
@Id public Long getID() {
return id;
}
...
Persistence Entity Example (Contd.)
...
// More code
Demo
Creating Entities from Existing
Database tables
Persistence Context &
Entity Manager
Persistence – Key Concepts
Persistence
creates
PersistenceUnit EntityManager
Configured by Factory
creates
PersistenceContext EntityManager
Manages
Persistence Context
• Set of managed entities, belonging to a single
persistence unit
• “Entity instance is in managed state”means it is
contained in a persistent context
• Inclusion or exclusion of an entity into/from the
persistence context will determine the outcome of any
persistence operation on it
• Not directly accessible to application, it is accessed
indirectly through entity manager – type of entity
manager determines how a persistence context is
created and removed
EntityManager
• API to manage the entity instance lifecycle
• Allows your program to interact with underlying
persistence engine
• Similar in functionality to Hibernate Session,
JDO PersistenceManager, etc.
• Provides the following functionalities
> Lifecycle operations – persist(), remove(), refresh(), merge()
> Finder – find(), getReference()
> Factory for query objects – createNamedQuery(),
createQuery(), createNativeQuery()
> Managing persistence context – flush(), clear(), close(),
getTransaction(), ...
Entity Lifecycle State Diagram
> New entity instance is created
no longer associated with
> Entity is not yet managed or persistent persistence context
new()
New PC ends Detached
Updates
persist()
> Entity becomes managed Managed merge()
> Entity becomes persistent > State of detached entity is
in database on transaction merged back into
commit managed entity
remove()
return order;
}
Find and Remove Operations
@TransactionAttribute(TransactionAttributeType.REQUIRED) //Default
public void logTransaction(int empId, String action) {
// verify employee number is valid
if (em.find(Employee.class, empId) == null) {
throw new IllegalArgumentException("Unknown employee id");
}
LogRecord lr = new LogRecord(empId, action);
em.persist(lr);
}
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public void logTransaction2(int empId, String action) {
logTransaction(empId, action);
}
Transactions & Persistence Context
Example
@Stateless
public class EmployeeServiceBean implements EmployeeService {
@PersistenceContext(unitName="EmployeeService")
private EntityManager em;
@EJB
AuditService audit;
●
Support for basic, serialized objects and LOBs
● Unary, n-ary relationship mappings
●
Rules for defaulting of DB table and
column names
● Access to object state using fields or properties
● Multiple tables, composite relationship keys
37
Simple Mappings
38
Simple Mappings
CUSTOMER
ID NAME C_RATING PHOTO
@Entity(access=FIELD)
public class Customer {
@Id
int id;
String name;
int c_rating;
@Lob
Image photo;
}
39
Simple Mappings CUSTOMER
ID NAME CREDIT PHOTO
@Entity(access=FIELD)
public class Customer {
@Id
int id;
String name;
@Column(name=“CREDIT”)
int c_rating;
@Lob
Image photo;
}
CUSTOMER PHONE
ID ... ID ...
CUSTOMER_PHONE
ID CUSTS_ID PHONES_ID
Animal
id: int
name: String
LandAnimal AirAnimal
ANIMAL
ID NAME
Joined:
LAND_ANML AIR_ANML
each class is stored in
ID LEG_COUNT ID WING_SPAN
a separate table
LAND_ANML AIR_ANML
Table per Class:
ID NAME LEG_COUNT ID NAME WING_SPAN
// Child Entity
@Entity
public class Student extends Person {...}
private String school;
private double grade;
// Child Entity
@Entity
public class Teacher extends Person {...}
Single Table Strategy Example
Single Table Strategy Example
Joined Strategy
// Child Entity
@Entity
public class Student extends Person {...}
private String school;
private double grade;
// Child Entity
@Entity
public class Teacher extends Person {...}
Demo
Use different strategies for
inheritance and how database
tables are created
- SINGLE_TABLE
- JOINED
Entity Inheritance Strategy
• SINGLE_TABLE [default]
> All the classes in a hierarchy are mapped to a single table
> This strategy provides good support polymorphic relationships between
entities and queries that cover the entire class hierarchy
> May contain null fields for some subclass data
• TABLE_PER_CLASS
> Each class in a hierarchy mapped to a separate table and hence,
provides poor support for polymorphic relationships
> requires SQ union or separate SQL queries for each subclass
• JOINED
> no null fields => compact data
> This provides good support for polymorphic relationships, but requires
one or more join operations – may result in poor performance
Embedded Objects
Embedded Objects
@Entity
public class Customer
{
@Id CUSTOMER
int id; ID NAME CREDIT PHOTO
@Embedded
CustomerInfo info;
}
@Embeddable
public class CustomerInfo {
String name;
int credit;
@Lob
Image photo;
}
Entity Listeners
Entity Listeners
• Listeners or callback methods are designated to receive
invocations from persistence provider at various stages of
entity lifecycle
• Callback methods
> Annotate callback handling methods right in the entity class or
put them in a separate listener class
> Annotations
> PrePersist / PostPersist
> PreRemove/ PostRemove
> PreUpdate / PostUpdate
> PostLoad
Entity Listeners: Example – 1
@Entity
@EntityListener(com.acme.AlertMonitor.class)
public class AccountBean implements Account {
Long accountId;
Integer balance;
boolean preferred;
public Long getAccountId() { ... }
public Integer getBalance() { ... }
@Transient context
public boolean isPreferred() { ... }
@PrePersist
public void validateCreate() {
if (getBalance() < MIN_REQUIRED_BALANCE)
throw new AccountException("Insufficient balance to
open an account");
}
@PostLoad
public void adjustPreferredStatus() {
preferred =(getBalance() >=
AccountManager.getPreferredStatusLevel());
}
}
Entity Listeners: Example – 3
@PostPersist
public void newAccountAlert(Account acct) {
Alerts.sendMarketingInfo(acct.getAccountId(),
acct.getBalance());
}
}
Summary,
Resources,
Sun Developer Network
Java Persistence Summary
• Simplifies persistence model
• Supports Light-weight persistence model
• Support both Java SE and Java EE environments
• O/R mapping through annotation
• Extensive querying capabilities
Resources
http://developers.sun.com/events/techdays/presentations/
71