Persistence SRitter
Persistence SRitter
3.0 &
Java Persistence APIs:
Simplifying
Persistence
Simon Ritter
Technology Evangelist
Sun Microsystems
1
What is Persistence?
• Saving (persisting) your application's data
> in Atomic, Consistency, Isolation, Durability
> Mapping real world concepts and models to the data store
(referred to as O/R)
• Expressing the inter-data relationship
> Multi-table support
> Inheritance
> Relationship cardinality and direction
• Data access
> Transactional
> Query interface
> High performance
2
What Do We Have Today?
• Standard persistence model
> Java Database Connectivity (JDBC)
> Java Data Objects
> Entity bean
• Open source and commercial implementations
> Hibernate
> Castor
> iBatis SQL Maps
> XORM
> TopLink
3
How Do They Differ?
JDBC JDO CMP
Centricity Database Object Application server
Query SQL JDOQL EJBQL
Transactions User managed User managed Container managed
Security User managed User managed Container managed
Relations Foreign keys Reachability Declarative
Portability Least Moderate Most
Felixibilty Most Moderate Least
Remoting No No Yes
Inheritence No Yes EJB 3.0
4
The Problem is ...
• Different persistence technology have different emphasis
> Can be confusing if you are a novice
• Can be complex and/or tedious to use
> Understanding concepts
> Tedious and error prone when implementing
• Use different technology on different Java platform
> JavaSE cannot use models created in EntityBeans
• No easy way to work with open source persistence
engines
5
A bit like this...
6
The Goal of Java Persistence
7
Simplifying/Unifying Persistence
• Part of JSR 220 (Enterprise JavaBeans 3.0)
> Began as simplification of Entity Beans
• Scope of persistence has expanded at request of
community to support uses in Java EE and Java SE
• Simpler, easier and smarter
> Easy to develop
> Unify development with Java object model – e.g. previous
versions of EJB do not support inheritance
> Supports typical use cases – configure by exception only
8
Primary Features
• POJO based programming/persistence model
> Simple Java classes – not components, only 1 file instead of 3
• Support for rich domain modelling
> Inheritance, polymorphism, etc
> Similar to Java programming
• Expanded query language
• Standardize object/relational mapping
> Standardize annotations and XML configuration files
> Allows more 3rd party support
• Usable in Java EE and Java SE environments
9
Data Model
and
O-R Mapping
Basic and Relationship
Entity Inheritance
Entity Identity
Order
An Example Data Model
int id
Customer M Customer cust
...
1
int id
String name
int c_rating
Image photo
Set<Order> orders M
Collection<Phone>
phones Phone
...
int id
Collection<Customer>
N custs
...
@Entity(access=FIELD)
public class Customer {
@Id
int id;
String name;
@Column(name=“CREDIT”)
int c_rating;
@Lob
Image photo;
}
@LOB public Image photo;
...
} Specify the table column to
map to
13
Entity Class for Customer – by Property
@Entity(access=PROPERTY) @Table(name = “customer”)
public class Customer {
private int id;
private String name;
@Id public int getId() { return (id); }
public void setId(int i) { id = i; }
public String getName() { return (name); }
public void setName(String n) { name = n; }
@Column(name=”CREDIT”) public int getC_rating() { ... }
public void setC_rating(int r) { ... }
@LOB public Image getPhoto() { ... }
public void setPhoto(Image i) { ... }
...
14
Entity Relationships
• One-to-one, one-to-many, many-to-many, many-to-one
relationships among entities
> Support for Collection, Set, List and Map
• Need to specify owning side in relationships
> Determines the update to the relationship in the database
> OneToOne relationship – the side with the foreign key
> OneToMany, ManyToOne – many side
• Specify constraints with 'cascade'
> ALL, PERSIST, UPDATE, DELETE
15
Relationship Mappings – OneToMany
@Entity(access=FIELD) @Entity(access=FIELD)
public class Customer { public class Order {
@Id @Id
int id; int id;
... ...
@OneToMany(mappedBy=“cust”) @ManyToOne
Customer cust;
Set<Order> orders; }
}
CUSTOMER ORDER
ID ... ID CUST_ID ...
16
Relationship Mappings – ManyToOne
@Entity(access=FIELD)
public class Customer {
@Id
int id;
@ManyToOne
Address addr;
}
ADDR_ID
CUSTOMER ADDRESS
ID ADDR_ID ID ...
CUSTOMER PHONE
ID ... ID ...
CUSTOMER_PHONE
CUSTS_ID PHONES_ID
CUSTOMER PHONE
ID ... ID ...
CUSTOMER_PHONE
CUSTS_ID PHONES_ID
@Entity(access=FIELD) @Embeddable(access=FIELD)
public class Customer { public class CustomerInfo {
@Id String name;
int id; int credit;
@Embedded Image photo;
CustomerInfo info; }
}
CUSTOMER
ID NAME CREDIT PHOTO
22
Entity Inheritance – (Abstract) Entity Class
@Entity(access=FIELD)
public class Animal {
@Id public int id;
public String name;
}
@Entity(access=FIELD)
public class LandAnimal extends Animal {
//Inherits id, name
public int legCount;
}
@Entity(access=FIELD)
public class AirAnimal extends Animal {
//Inherits id, name
public short wingSpan;
}
23
Entity Inheritance – Mapped Superclass
@MappedSuperClass
public class Animal {
@Id public int id;
public String name;
}
@Entity(access=FIELD)
public class LandAnimal extends Animal {
//Inherits id, name
public int legCount;
}
@Entity(access=FIELD)
public class AirAnimal extends Animal {
//Inherits id, name
public short wingSpan;
}
24
Entity Inheritance – Non Entity Class
public class Animal {
public String name;
}
@Entity(access=FIELD)
public class LandAnimal extends Animal {
//Inherits name but not persisted
@Id public int id;
public int legCount;
}
@Entity(access=FIELD)
public class AirAnimal extends Animal {
//Inherits name but not persisted
@Id public int id;
public short wingSpan;
}
25
Implementing Entity Inheritance
• Use Java application metadata to specify mapping
• Support for various inheritance mapping strategies
> Single table – all classes stored in the same table
> Table per class – each concrete class is stored in a
separate table
> Joined subclass – each class is stored in a separate
table
26
Object Model
Animal
id: int
name: String
LandAnimal AirAnimal
27
Data Models
ANIMAL
Single table:
ID DISC NAME LEG_CNT WING_SPAN
ANIMAL
ID NAME
Joined:
LAND_ANML AIR_ANML
ID LEG_COUNT ID WING_SPAN
LAND_ANML AIR_ANML
Table per Class:
ID NAME LEG_COUNT ID NAME WING_SPAN
28
Discriminator Column and Value
@Entity @Table(name="ANIMAL")
@Inheritance(strategy=SINGLE_TABLE)
@DiscriminatorColumnName(name=”DISC”)
@DiscriminatorValue(“ANIMAL”)
public class Animal {
@Id protected int id;
protected String name;
...
} ANIMAL
ID DISC NAME LEG_CNT WING_SPAN
@Entity @DiscriminatorValue("LANDANIMAL")
public class LandAnimal extends Animal {
@Column(name=”LEG_CNT”) protected int legCount;
...
29
Discriminator Value for SingleTable
30
Identity
• Every entity has a persistence identity
> Uniquely identifies that entity
> Maps to primary key in the database
• Identity can be application or database generated
• Must be defined on the ROOT of entity hierarchy or
mapped superclass
31
Types of Identity
• Simple
> @Id – single field/property in entity class
> @GeneratedValue
@Id @GeneratedValue(strategy=SEQUENCE)
@Column(name=”CUST_ID”) public int id;
• User defined
> @EmbeddedId – single field/property in entity class
//EmployeePK class must be @Embeddable
@EmbeddedId public EmployeePK pk;
> @IdClass – corresponds to multiple id field in entity class
@IdClass(EmployeePK.class)
@Entity public class Employee {
@Id String empName;
@Id int dept; 32
Using orm.xml for Mapping
• Can put some or all the mapping metadata in XML
mapping files
> orm.xml located in META-INF directory of JAR
• Can use orm.xml to specify entity mappings
> Annotations not required
• At runtime, orm.xml override annotations
33
Example of orm.xml File
Overriding the default
<entitymappings> annotations in source
<entity class=”Customer”>
<id name=”id”>
<generatedvalue/>
</id>
<basic name=”c_rating”>
<column name=”ratings”/>
</basic>
...
<onetomany name=”orders” mappedby=”cust”/>
</entity>
...
</entitymappings>
34
Persistence
EntityManager
Persistence Unit
Persistence Context
Entity Lifecycle
Application Managed Persistence
Transactions
Persistence – Key Concepts
• Entity manager
> Primary interface to interact with underlying persistence engine
• Persistence context
> A set of entities associated with a particular transaction
• Persistence unit
> A set of entities that are mapped to a single data store
• Transactions
36
Entity Manager
• Similar in functionality to Hibernate Session and
JDO PersistenceManager
• Allows the program to interact with underlying persistence
engine
• 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(), ...
37
Entity Manager Types
• Can be ONE of the following types
> JTA – transaction context propagated
> RESOURCE_LOCAL – transaction context not
propagated
• Obtained via the following ways
> Container managed
>Via resource injection or JNDI lookup
>Always JTA
> Application managed
>Created by EntityManagerFactory
>May be JTA or RESOURCE_LOCAL
38
EntityManager Example Resource injection
@Stateless public ShoppingCartBean
implements ShoppingCart {
@PersistenceContext EntityManager entityManager;
public OrderLine createOrderLine(Product product
, Order order) {
OrderLine orderLine = new OrderLine(order, product);
entityManager.persist(orderLine);
return (orderLine);
}
public OrderLine updateOrderLine(OrderLine orderLine) {
return (entityManager.merge(orderLine));
}
} 39
Entity Life-cycle
New Entity
• Created using new keyword
New • Has no persistent identity or state
entity
Managed Entity
• Has a persistent identity
Managed • Associated with a persistence context
entity Detached Entity
• Has a persistent identity
Detached • Is no longer associated with
entity persistence context
Removed Entity
Removed • Has a persistent identity
entity • Associated with persistence context
• Is scheduled to be deleted from the
database 40
Entity Lifecycle Illustrated – The Diagram
remove()
Removed
41
Entity Lifecycle Illustrated – The Code
@Stateless public ShoppingCartBean
implements ShoppingCart { New entity
@PersistenceContext EntityManager entityManager;
public OrderLine createOrderLine(Product product
, Order order) {
OrderLine orderLine = new OrderLine(order, product);
entityManager.persist(orderLine); Managed entity
return (orderLine);
} Detached entity
public OrderLine updateOrderLine(OrderLine orderLine) {
return (entityManager.merge(orderLine));
}
}
42
Detached Objects as DTOs
Returned to callee as a POJO
public OrderLine updateOrderLine(
OrderLine orderLine) { Detached
return(entityManager.merge(orderLine));
Detached
}
Managed
43
Persistence Unit
• All entities managed by a single EntityManager is defined
by a persistence unit
• A persistence unit defines
> all entities that are colocated
> mapped onto a single database
• persistence.xml defines one or more persistence unit
<persistenceunit name="OrderManagement">
<mappingfile>mappings.xml</mappingfile>
<jarfile>order.jar</jarfile>
<transactiontype>JTA</transactiontype>
</persistenceunit>
44
Persistence Unit
same entity
Data source
45
Persistence Contexts
• A set of managed entity instances belonging to a single
persistence unit
> Entities that have been read from the data store
> Entities that will be written back to the data store
• Persistence contexts may be
> Transaction scoped – persistence context ends when a
transaction ends
> Managed entities will become detached
> Extended – spanning over multiple sequential transactions
> Used only within a StatefulSessionBean
46
Types of Persistence Context
• May be managed by container or application
• Container managed persistence context
> Obtained by injection or JNDI lookup
> Propagated across components with JTA transaction
> May be single or extended scope
• Application managed persistence context
> Provided for use in Java EE and Java SE
> Obtained from EntityManagerFactory
> Scope is managed by application
• Web tier supports both types
47
Container Managed Persistence Context
@Stateless public ShoppingCartBean
implements ShoppingCart {
@PersistenceContext EntityManager entityManager;
public OrderLine createOrderLine(Product product
, Order order) {
OrderLine orderLine = new OrderLine(order, product);
entityManager.persist(orderLine);
return (orderLine);
}
Persistence context
public OrderLine updateOrderLine(OrderLine orderLine) {
return (entityManager.merge(orderLine));
}
}
48
Application Managed Persistence Context
public class MyServlet extends HttpServlet {
@PersistenceUnit(unitName=”OrderManagement”)
EntityManagerFactory factory;
public void doGet(HttpServletRequest req, ...) {
//Get an instance of EntityManager
EntityManager em = factory.createEntityManager();
//Create a transaction
EntityTransaction tx = em.getTransaction();
...
//Commit the transaction or rollback
tx.commit();
//Close EntityManager
em.close();
}
...
49
EntityManager in JavaSE
• Application must use “bootstrap API” to obtain an
instance of EntityManagerFactory
• Typically use resource-local EntityManagers
> Application uses a local EntityTransaction obtained from the
EntityManager
• New persistence context for each and every
EntityManager that is created
• No propagation of persistence context
50
Bootstrap Classes
• javax.persistence.Persistence
> Root class for boot strapping the EntityManager
>Injected resource in Container
> Returns EntityManagerFactory for creating named
EntityManager configuration
• javax.persistence.EntityManagerFactory
> Creates an EntityManager from a named persistence
unit
51
Extended Persistence Context – When?
• Use when a conversation is required
> When a user's interaction that spans more than a single request
• Convenient and efficient to keep and reuse references to
entities that are the subject of the conversation
> HTTPSession, stateful session bean, models in JavaSE
applications
• EntityManager with extended persistence context
maintains these entity references after a transaction has
committed
• Entities remains managed and cached over multiple
transaction
> Becomes detached when EntityManager is closed or when
session bean is removed 52
Extended Persistence Context
@Statelful public class ShoppingCart {
//Specify that we want an EXTENDED
@PersistenceContext(type=PersistenceContextType.EXTENDED)
EntityManager em;
//Cached order
private Order order;
//For returning customer who have saved order
public void lookupOrder(String id) {
//customer remains managed for the lifetime of the bean
order = em.find(Order.class, id);
}
53
Transaction Demarcation
• JTA transaction
> UserTransaction are injected
• Resource local transactions
> EntityTransaction from EntityManager
• Container managed entity managers are JTA
• Appication managed entity managers are either JTA or
RESOURCE_LOCAL
> Determined my configuration in persistence.xml
> JavaSE are always resource local
54
JTA Transaction
@Resource UserTransaction utx;
@PersistenceUnit EntityManagerFactory factory;
public void createDistributor(String n) {
//Begin transaction
utx.begin();
EntityManager em = emf.createEntityManager();
//Create entity
Distributor dist = new Distributor();
dist.setName(n);
//Save it
em.persist(dist);
//Commit transaction and close EntityManager
utx.commit();
em.close();
} 55
RESOURCE_LOCAL Transaction
// Create EntityManagerFactory for a persistence unit
// called manager1
EntityManagerFactory emf =
Persistence.createEntityManagerFactory("manager1");
EntityManager em = emf.createEntityManager();
// Get a transaction instance and start the transaction
EntityTransaction tx = em.getTransaction();
// Create a new customer,persist and commit it.
tx.begin();
Distributor dist = new Distributor();
dist.setName("Joe Smith");
em.persist(dist);
tx.commit();
em.close();
emf.close();
56
Queries
EJB Query Syntax
Named, Dynamic, Native Queries
Polymorphic Queries
Java Persistence Query Language
• SQL-like query language
• Operates over abstract persistence schema of the entities
> Queries are not expressed in terms of the persistence store
• Provides functionality like select, update and delete
• Portable across databases
58
Query Language Features
• Bulk update and delete operations
• Group By / Having
• Subqueries
• Additional SQL functions
> UPPER, LOWER, TRIM, CURRENT_DATE, ...
• Polymorphic queries
• Support for dynamic queries or ad-hoc queries in addition
to named queries or static queries
59
Named Queries
@NamedQuery(
name=“findCustomersByName”,
queryString=
“SELECT c FROM Customer c”
+ “WHERE c.name LIKE :custName”
)
@PersistenceContext public EntityManager em;
Query query = em.createNamedQuery(
“findCustomersByName”);
query.setParameter(“custName”, “smith”)
List customers = query.getResultList();
60
Dynamic Queries
public List findWithName (String name) {
Query query = em.createQuery (
“SELECT c FROM Customer c”
+ “ WHERE c.name LIKE :custName”)
query.setParameter(“custName”, name);
query.setMaxResults(10);
return (query.getResultList());
}
61
Native Queries
Query q = em.createNativeQuery(
"SELECT o.id, o.quantity, o.item, i.id, i.name, i.desc" +
"FROM Order o, Item i " +
"WHERE (order_quantity > 25) AND (order_item = i.id)",
"OrderResults");
@SqlResultSetMapping(name="OrderResults",
entities={
Mapping info for
@EntityResult(
entityClass=com.acme.Order.class,
non default fields
fields={
@FieldResult(name="id", column="order_id"),
@FieldResult(name="quantity",
column="order_quantity"),
@FieldResult(name="item",
column="order_item")}),
@EntityResult(entityClass=com.acme.Item.class)}
)
62
Polymorphic Queries
• All Queries are polymorphic by default
> That is to say that the FROM clause of a query designates not
only instances of the specific entity class(es) to which it
explicitly refers but of subclasses as well
63
Advance Query API
• Scrolling through result set
Query q = em.createQuery(“select e from Employee e”
, Employee.class);
//Set cursor to the 6th record
q.setFirstResult(5);
//Retrieve only 100 employess
q.setMaxResult(100);
Collection<Employee> emps = q.getResultList();
• Query hints
q.setHint(“toplink.cacheusage”, 2);
q.setHint(“toplink.pessimisticlock”, 1);
64
Querying with Compound Keys – 1
public class WarehousePK implements Serializable {
private String city;
private String code;
public void setCityCode(String c) {
city = c;
}
public String getCityCode() {
return (city);
}
public void setWarehouseCode(String c) {
code = c;
}
public String getWarehouseCode() {
return (code);
}
}
65
Querying with Compound Keys – 2
@Entity(access=FIELD)
@IdClass(WarehousePK.class)
public class Warehouse {
@Id @Column(name=”W_NAME”)
public String warehouseCode;
@Id public String cityCode;
...
}
@PersistenceContext EntityManager em;
WarehousePK pk = new WarehousePK();
pk.setCityCode(“CSIN05”);
pk.setWarehouseCode(“JRE07”);
Warehouse warehouse = em.find(Warehouse.class, pk);
66
Best Practices
and
Gotchas
Things to Remember about Entity
• Entity are not EntityBeans!
• Entity are POJOs
> No remote calls involved
> Methods are executed locally not on the server/container
> Methods can now be coarse or fine grained
> Remember to merge() your results
• No remote or local Entity, all Entity are either
> New, Managed, Deteched, Removed
• Entity not in a transaction context, Entity are detached
once fetched
> In either JTA or RESOURCE_LOCAL
> Can now have coarse and fine grained methods
68
Going from Local to Member
• Resource injections only works with instance members
> Have implications on how you use them
• May have potential access issues
> Race conditions
Old
public void doGet(HttpServletRequest req, ...) {
MyStatelessSession ses = sesHome.create();
ses.doSomething();
ses.remove();
New
@EJB MyStatelessSession ses;
public void doGet(HttpServletRequest req, ...) {
ses.doSomething();
...
69
Threading Models and Injection
• Certain objects are not threadsafe
> Typically stateful objects lik EntityManager
• Certain components are multi threaded
> Especially stateless objects like Servlets
• It is dangerous to inject non threadsafe objects into
stateless components!
• May result in
> Inconsistent data
> Data viewable to other users
70
Beware of Injected Objects
public class ShoppingCartServlet extends HttpServlet {
@PersistenceContext EntityManager em;
protected void doPost(HttpServlet req, ...) {
Order order order = ...;
}
em.persist(order);
WRONG
public class ShoppingCartServlet extends HttpServlet {
@PersistenceUnit EntityManagerFactory factory;
protected void doPost(HttpServlet req, ...) {
EntityManager em = factory.createEntityManager();
Order order order = ...;
em.persist(order);
} CORRECT
71
Maintaining Relationship
• Application bears the responsibility of maintaining
relationships
Before After
LineItem1 LineItem1
OrderA OrderA
LineItem2 LineItem2
Inconsistent!
OrderA.lineItem.add(LineItem3);
72
Inheritance
• All Java persistence queries are polymorphic
• Single table per class hierarchy
> Provides good support for polymorphic queries
• Single table, joined subclass
> Requires unions
73
Flush Mode
• Control whether we synchronize the state of the managed
entities before a query
• Applicable only if there is an active transaction
• Possible values are
> AUTO – immediate. This is the default
> COMMIT – flush only when transaction commits
> NEVER – invoke EntityManager.flush() manually
74
Flush Mode - AUTO vs COMMIT
//Assume JTA transaction
Order order = em.find(Order.class, orderNumber);
//Add some line item
order.addLineItem(....);
Query q = em.createNamedQuery(“findAllLineItemByOrderID”);
q.setParameter(“id”, orderNumber);
//Newly added item visible – default is AUTO
List list = q.getResultList();
//Assume JTA transaction
Order order = em.find(Order.class, orderNumber);
//Add some line item
order.addLineItem(....);
Query q = em.createNamedQuery(“findAllLineItemByOrderID”);
q.setParameter(“id”, orderNumber);
q.setFlushMode(FlushModeType.COMMIT);
//Newly added item is NOT visible
List list = q.getResultList();
75
Locking
• EJB 3.0 specification assumes
> Optimistic locking based on version consistency
• All relationships with @Version included in check
> Not used by application
@Entity class Order {
@Version public TimeStamp version;
• In highly concurrent environment, pessimistic locking may
be a better option
> Optimistic locking may result in lots of rollbacks
> Vendor specific
query.setHint(“toplink.pessimisticlock”, 1);
http://docs.sun.com/app/docs/doc/819-3659/6n5s6m598?a=view
76
Persistence Context
Does it affect performance?
Micro benchmark with lots of lookups
100% Extended
90% Transactional
80%
70%
60%
50%
40%
30%
20%
10%
0%
tx/sec
Source: Internal benchmarks
77
Transactions
• Do not perform expensive and unnecessary operations
that are not part of transaction
> Hurt performance
> E.g. logging – disk write expensive, resource contention on log
• May want to ignore transaction when browsing data
> Create your own EntityManager
• Propagation of EntityManagers between components
> Create EntityManager in JTA transaction
> If EntityManager created outside of JTA transaction, use
joinTransaction()
EntityManager em = factory.createEntityManager();
utx.begin();
em.joinTransaction();
Join this transaction
78
Transactions in Web Tier
• Servlet container may flush response to browser at any
time
• So may display success to user when transaction fails
protected void doPost(HttpServletRequest res,
HttpServletResponse res) throws ... {
String itemCode = req.getParameter(“item_code”);
int count = Integer.parseInt(req.getParameter(“count”));
PrintWriter write = res.getPrintWriter();
write.println(“You have purchased “ + count + “ items”);
//Business logic – EntityManager with JTA or RESOURCE_LOCAL
addToCart(itemCode, count);
write.flush();
write.close(); Message may have
gone back to the client
• Use an extended persistence context – conversation
> Remember Stateful session bean 79
Conversation
@Stateful public class OrderBean {
@PersistenceContext(type=EXTENDED) EntityManager em;
public void add(String itemCode, int qty) { ... }
public void confirmOrder() { ... }
...
}
protected void doPost(HttpServletRequest req, ...) throws ... {
String cmd = req.getParameter(“cmd”);
if (cmd.equals(“NEW”)) {
//Create stateful session bean, hold in HttpSession
req.getSession().setAttribute(“order”, orderBean);
} else if (cmd.equals(“ADD_ITEM”)) {
//Add item to order bean
orderBean.add(...);
} else if (cmd.equals(“CONFIRM”)) {
orderBean.confirmOrder();
order.remove();
req.getSession().removeAttribute(“order”);
}
80
Fetch Types
• Data fetching strategy
> EAGER – immediate
> LAZY – load data only when needed
> Hint when FetchType is LAZY
• FetchType LAZY benefits large objects and relationships
with deep hierarchies
> Used when field or relationship not accessed immediately
• Default is EAGER except for 1:m and m:n relationships
• EAGER is used when accessing entity outside of a
transaction
> Entity are detached immediately
81
Cascade Type
• Specifies operations cascaded to associated entities
• Used for relationships
> ALL, PERSIST, MERGE, REMOVE, REFRESH
> Default is none
@Entity public class Order {
@OneToMany(cascade=PERSIST, fetch=LAZY)
Collection<LineItems> lineItems;
@Entity public class LineItem {
@ManyToOne public Order order;
@OneToMany
public Collection<ProductCode> pIds;
...
Order order = new Order();
//add some line item to order Not managed
em.persist(order);
83
EJB 3.0 Persistence Summary
• All new Entities
> Simplifies persistence model
> Supports Light-weight persistence model
> Support both J2SE and J2EE environments
> Extensive querying capabilities
• Understand the data model
> Use correct O/R model
> Use appropriate loading scheme
> Need to understand how persistence engine works
84
Questions?
Enterprise JavaBean
3.0
and
Java Persistence
APIs:
Lee Chuk Munn
[email protected]
Simplifying
Staff Engineer
Persistence
Sun Microsystems
86