Java Persistence API JPA Basics
Java Persistence API JPA Basics
Agenda
Java Persistence Requirements O/R Mapping What is an entity? JPA Programming Model Entity Manager & life-cycle operations Detached Entities Entity life-cycle transition Persistence context and Entity Manager Transactions
Data lives in the relational database, which is table driven (with rows and columns)
What is JPA?
Java EE standard O/R Mapping framework Object/relational mapping framework for enabling transparent POJO persistence
Let you work without being constrained by tabledriven relational database model handles ObjectRelational impedance mismatch
Provide extensive querying capabilities Support for pluggable, third-party persistence providers
EJB applications
10
O/R Mapping
O/R Mapping
Comprehensive set of annotations defined for mapping
> > > > >
Relationships Joins Database tables and columns Database sequence generators Much more
Specified using standard description elements in a separate mapping file or within the code as annotations
12
Order
M
int id Customer cust ...
Phone
N
int id Collection<Customer> custs ...
13
Simple Mapping
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; }
Mapping defaults to matching column name. Only configure if entity field and table column names are different.
14
What is an Entity?
What is an Entity?
Plain Old Java Object (POJO)
> Created by means of new keyword just like a normal Java
class > No need to implement interfaces unlike EJB 2.1 entity beans
Can extend other entity and non-entity classes Serializable; usable as detached objects in other tiers
> No need for data transfer objects
16
Entity 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;} }
17
Entity Identity
Every entity has a persistence identity Can correspond to simple type
> Maps to primary key in database > @Idsingle field/property in entity class > @GeneratedValuevalue can be generated automatically
> @EmbeddedIdsingle field/property in entity class > @IdClasscorresponds to multiple Id fields in entity class
18
Programming Model
as Entity
21
// Relationship between Customer and Orders @OneToMany public Collection<Order> getOrders() { return orders; } public void setOrders(Collection<Order> orders) { this.orders = orders; } // Other business methods ...
22
} }
23
24
EntityManager
Similar in functionality to Hibernate Session, JDO PersistenceManager, etc. Controls life-cycle of entities
> > > >
persist() - insert an entity into the DB remove() - remove an entity from the DB merge() - synchronize the state of detached entities refresh() - reloads state from the database
26
Persist Operation
public Order createNewOrder(Customer customer) { // Create new object instance entity is in transient state Order order = new Order(customer); // After persist() method is called upon the entity, // the entity state is changed to managed. On the // next flush or commit, the newly persisted // instances will be inserted into the database table. entityManager.persist(order); return order;
27
Merge Operation
public OrderLine updateOrderLine(OrderLine orderLine) { // The merge method returns a managed copy of // the given detached entity. Changes made to the // persistent state of the detached entity are // applied to this managed instance. return entityManager.merge(orderLine); }
29
Detached Entities
Detached Entities
Must implement Serializable interface if detached object has to be sent across the wire No need for DTO (Data Transfer Object) anti-design pattern Merge of detached objects can be cascaded
31
32
Entity Life-cycle
34
Demo #1
1. Creating Entities from Existing Database tables 2. Performing CRUD (Create, Read, Update, Delete) operations against Entities You can try this demo from www.javapassion.com/handsonlabs/ jpabasics
particular persistent context > Entity instances in a particular persistent context behaves in a consistent manner
Entity manager
> Performs life-cycle operations on entities manages
persistence context
37
context there is no need > Persistence context is accessed indirectly through entity manager
The type of entity manager determines how a persistence context is created and removed Why do you care as a developer?
> Because inclusion or exclusion of an entity into/from the
40
an application through @PersistenceContext annotation the container creates an entity manager and injects it into the application > Application-managed entity manager (for Java SE) is created and closed by the application itself
41
Demo #2
Creating Entity Manager for Java SE Environment
You can try this demo from www.javapassion.com/handsonlabs/ jpabasics
Entity manager
43
transactional scope
45
Persistence Unit
Persistence Unit
All entities managed by a single EntityManager is defined by a persistence unit A persistence unit defines
> all entities that are co-located > mapped onto a single database
Persistence Unit
Persistence Context same entity
Entity Manager Entity Manager
Persistence Context
Data source
48
Transactions
Transaction Types
Two different transaction types
> Resource-local transactions > JTA (Java Transaction API) > Multiple participating resources > Distributed XA transactions
50
@TransactionAttribute Annotation
TransactionAttributeType.REQUIRED TransactionAttributeType.REQUIRES_NEW TransactionAttributeType.MANDATORY TransactionAttributeType.NOT_SUPPORTED TransactionAttributeType.NEVER TransactionAttributeType.SUPPORTS
51
managers
52
53
Demo #3
Use two different transaction attributes and see how persistence context is propagated. You can try this demo from www.javapassion.com/handsonlabs /jpabasics
Demo Scenarios
There are two stateless beans
> EmployeeServiceBean (Calling bean) > AuditServiceBean (Callee bean)
#1: The createEmployee() method of the EmployeeServiceBean invokes logTransaction() method of the AuditServiceBean
> logTransaction() is set with
TransactionAttributeType.REQUIRED annotation
#2: The createEmployee2() method of the EmployeeServiceBean invokes logTransaction2() method of the AuditServiceBean
> logTransaction2() is set with
TransactionAttributeType.REQUIRES_NEW annotation
55
56
57
TransactionAttributeType.REQUIRED annotation
The createEmployee() method of Bean #1 starts a new transaction A as default, thus creating a persistence context A
> The newly created Employee object A belongs to persistence context A
The transaction A and persistence context A of createEmploy() method of Calling bean is propagated to the logTransaction() method of Callee bean
> The logTransaction() method has access to Employee object A
58
Thank You!
60