You are on page 1of 21

Java Persistence API:

Best Practices
Carol McDonald
Java Architect

1
Agenda

>Entity Manager
>Persistence Context
>Entities
>Schema & Queries
>Transaction

2
EntityManager set of entities managed by
API for managing entities Entity Manager

EntityManager
persist()
remove()
refresh()
merge()
find()
createQuery()
createNamedQuery()
Persistence
contains()
Context
flush()

3
Catalog Java EE Application

Registration Application
Managed Bean Entity Class

Item
DB

ManagedBean Catalog
Session
JSF Components Bean

4
S t a t e l e s s S e s s io n
B e a n A n n o t a t io n

EJB EntityManager Example D e p e n d e n c y In j e c t io n

@Stateless
public class Catalog implements CatalogService {

@PersistenceContext(unitName=”PetCatalogPu”)
EntityManager em;

@TransactionAttribute(NOT_SUPPORTED)
public List<Item> getItems(int firstItem,
int batchSize) {
Query q = em.createQuery
("select i from Item as i");
q.setMaxResults(batchSize);
q.setFirstResult(firstItem);
List<Item> items= q.getResultList();
return items;
} 5
Catalog Spring JPA Application

Registration Application
Managed Bean Entity Class

Item
DB

ItemController
Catalog
Spring
JSF Components Bean
Spring
Framework

6
Spring with JPA
Component Stereotype
@Repository Spring transactions use aop
@Transactional
public class CatalogDAO implements CatalogService {

@PersistenceContext(unitName="PetCatalogPu")
private EntityManager em;

@Transactional(readOnly=true)
public List<Item> getItems(int firstItem,int batchSize) {
Query q =
em.createQuery("select object(o) from Item as o");
q.setMaxResults(batchSize);
q.setFirstResult(firstItem);
List<Item> items= q.getResultList();
return items;
}

7
Container vs Application Managed
Container managed entity managers (EJB, Spring Bean,
Seam component)
• Injected into application
• Automatically closed
• JTA transaction – propagated
Application managed entity managers
> Used outside of the JavaEE 5 platform
> Need to be explicitly created
● Persistence.createEntityManagerFactory()

> RESOURCE_LOCAL transaction – not propagated


> Need to explicitly close entity manager

8
Agenda

>Entity Manager
>Persistence Context
>Entities
>Queries
>Transaction

9
Persistence Context set of entities managed by
• Persistence context acts Entity Manager
as a first level cache for
entities EntityManager

• Two types of persistence persist()


remove()
context
refresh()
> Transaction scoped
merge()
> Extended scoped find()
persistence context createQuery()
createNamedQuery()
Persistence
contains()
Context
flush()

10
Level1 and Level2 caches
Persistence Context is a Level 1 cache

Transaction Transaction Transaction

Persistence Context Persistence Context Persistence Context


(EntityManager) (EntityManager) (EntityManager)

L2 Cache
(Shared Cache)

Entity managers for a specific PersistenceUnit on a given Java Virtual Machine (JVM ™)

“Java Virtual Machine” and “JVM” mean a Virtual Machine for the Java ™ Platform. Source:http://weblogs.java.net/blog/guruwons/archive/2006/09/unde
11
Entity Lifecycle
new()
New Detached
Entity Entity
Updates PC ends
persist()
Persistence Context Merge()
Managed find()
Managed Managed
Entity
Entity Entity

Guaranteed Scope of Transaction commit


Object Identity
only one manage entity
in PC represents a row
remove()
Removed
Entity
12
Entity Lifecycle Illustrated – The Code
@Stateless public ShoppingCartBean New entity
implements ShoppingCart {
Persistence c
@PersistenceContext EntityManager entityManager;

public OrderLine createOrderLine(Product product


, Order order) {
OrderLine orderLine = new OrderLine(order, product);
entityManager.persist(orderLine);
return (orderLine); Managed entity
}
Detached entity
}
13
Scope of Identity
@Stateless public ShoppingCartBean implements ShoppingCart {

@PersistenceContext EntityManager entityManager;Persistence co

public OrderLine createOrderLine(Product product,Order order)


OrderLine orderLine = new OrderLine(order, product);
entityManager.persist(orderLine);
OrderLine orderLine2 =entityManager.find(OrderLine,
orderLine.getId()));
(orderLine == orderLine2) // TRUE
return (orderLine);
} Multiple retrievals of the same object return references to the same o

}
14
Persistence Context
• Two types of persistence context
• Transaction scoped
> Used in stateless components
> Typically begins/ends at request entry/exit points
respectively
• Extended scoped persistence context

15
Persistence Context Propagation

@Stateless public class ShoppingCartBean implements


ShoppingCart {
@EJB InventoryService inv;
@EJB OrderService ord;

public void checkout(Item i, Product p) {


inv.createOrder(item);
ord.updateInventory(Product p)
} Persistence context
}

16
Persistence Context Propagation

@Stateless public class OrderServiceBean implements


OrderService {
@PersistenceContext EntityManager em1;
public void createOrder(Item item) {
em1.persist(new Order(item));
}
}
@Stateless public class InventoryServiceBean implements
InventoryService {
@PersistenceContext EntityManager em2;
public void updateInventory(Product p) {
Product product = em2.merge(p);
...
17
Declarative Transaction Management
Example

Check Out
New Persistence Persistence Context
Context Propagated
Shopping PC
1. Update Inventory PC
Cart Inventory Service
TX_REQUIRED TX_REQUIRED

Order PC
2. Create Order Service
Transaction
TX_REQUIRED
Attributes

18
AuditServiceBean

@Stateless
public class AuditServiceBean implements AuditService {
@PersistenceContext
private EntityManager em; NEW
PC !

@TransactionAttribute(REQUIRES_NEW)
public void logTransaction2(int id, String action) {
LogRecord lr = new LogRecord(id, action);
em.persist(lr);
}

19
Declarative Transaction Management
Example 2

Check Out
New Persistence Persistence Context
Context Propagated
Shopping PC
1. Update Inventory PC
Cart Inventory Service
REQUIRED REQUIRED

Audit PC2
2. log transaction Service
Transaction
REQUIRES_NEW
Attributes
NEW
PC !
20
Persistence Provider PC Transaction Features

• Attribute-level change tracking


• Only the minimal updates are sent to the database
• Orders INSERT, UPDATE and DELETE statements
• Minimizes database interactions
• EntityManager flush SQL prior to commit

21

You might also like