java.sun.com/javaone/sf
| 2004 JavaOne
SM
Conference | Session TS-2836
1
Enterprise
JavaBeans
TM
(EJB™)
3.0 Architecture
Simplified Persistence
Linda DeMichiel
EJB™ Specification Lead
Sun Microsystems
java.sun.com/j2ee
| 2004 JavaOne
SM
Conference | Session TS-2836
2
Goal of This Talk
Learn about the new simplifications to
persistence in the EJB™ 3.0 architecture
| 2004 JavaOne
SM
Conference | Session TS-2836
3
What’s New?
POJO Entity Beans
| 2004 JavaOne
SM
Conference | Session TS-2836
4
Agenda
Goals of
EJB™
3.0 Architecture
Why We Need to Simplify Persistence
EJB™
3.0 Entity Bean Drill Down
Entity Bean Goals
Simplified Persistence Model
Query Language Enhancements
Summary and Current Status
Where to Get More Info at JavaOne
SM
Conference
| 2004 JavaOne
SM
Conference | Session TS-2836
5
EJB™ 3.0 Architecture Expert Group
Agenda
•
Simplify EJB™ architecture—make it easier
to use
─
Improve developer productivity
─
Facilitate test-driven development
•
Capture broader range of developers
•
Conduct critical examination of EJB™
architecture complexity
•
Entity Beans are one of the more complex areas
of EJB™ architecture
─
Need to simplify them too
| 2004 JavaOne
SM
Conference | Session TS-2836
6
EJB™ 3.0 Architecture Expert Group
Apache Software Foundation:
Jeremy Boynes
BEA: Seth White, Cedric Beust
Borland: Jishnu Mitra
E.piphany: Reza Behforooz
Fujitsu-Siemens: Anton
Vorsamer
IBM: Jim Knutson
IONA: Conrad O'Dea
JBoss: Marc Fleury, Gavin King
Nokia: Vic Zaroukian
Novell: YongMin Chen
Oracle: Michael Keith, Olivier
Caudron
Pramati: Hemant Khandelwal
SAP: Harald Mueller
SAS Institute: Rob Saccoccio
SeeBeyond: Ugo Corda
Sun Microsystems: Linda
DeMichiel
Sybase: Evan Ireland
Tibco: Shivajee Samdarshi
Tmax Soft: JaeWoong Chung,
Woo Jin Kim
Individuals:
David Blevins
Scott Crawford
Olivier Ihns
Richard Monson-Haefel
Suneet Shah
| 2004 JavaOne
SM
Conference | Session TS-2836
7
Agenda
Goals of EJB™ 3.0 Architecture
Why We Need to Simplify Persistence
EJB™ 3.0 Entity Bean Drill Down
Entity Bean Goals
Simplified Persistence Model
Query Language Enhancements
Summary and Current Status
Where to Get More Info at JavaOne
SM
Conference
| 2004 JavaOne
SM
Conference | Session TS-2836
8
EJB™ Architecture Persistence
(Pre-EJB
™
3.0 Architecture)
•
Persistence management is a service that the
EJB™ container provides
─
As a service, persistence management is API based
─
Uses programming protocols, service hooks,
callback facilities, ...
─
Entity beans must be written to container contracts
─
Integrated with other EJB™ architecture services
(relationships, query, transactions, security, ... )
─
Intended as an ease-of-development facility
•
What is needed now is simpler model, better
modeling and query capabilities, + quality
of service
| 2004 JavaOne
SM
Conference | Session TS-2836
9
EJB™ 1.1 Architecture CMP
•
Instance-variable based “transparent” approach
─
Developer denotes persistent state
─
Container provides persistence management
•
What was wrong with it?
─
Remote components, coarse-grained, heavyweight
─
Did not scale performance-wise or modeling-wise
─
No associations
─
Non-portable finder methods only
─
Not really meant for O/R mapping
| 2004 JavaOne
SM
Conference | Session TS-2836
10
EJB™ 2.0 Architecture CMP
•
Froze development of EJB™ 1.1 architecture
approach and started over
•
Introduced get/set model
─
Rejected instance-variable-based approach
─
Hooks for dirty detection; management of faulting
─
Get method returns a copy
─
Relationships managed by container (CMRs)
•
Entity beans are (always) persistent objects
─
Creating an entity bean creates a persistent object
─
CMP and CMR “fields” are always persistent
•
Targeted at local access, not remote
| 2004 JavaOne
SM
Conference | Session TS-2836
11
EJB™ 2.0 Architecture
Persistence Model
•
Enables light-weight implementation
─
Entities typically accessed through local interfaces
─
Transactions typically started in session bean
or Web tier
─
Methods are often “unchecked”
•
Provides a standardized SQL-like query
language integrated with entity model
(EJB™ QL)
•
Usage has supplanted that of BMP
─
Held back by need for more EJB™ QL
─
High-quality, high-performance implementations
well-established in industry
| 2004 JavaOne
SM
Conference | Session TS-2836
12
What’s the Problem?
•
Formal model
─
Targeted at encapsulation of management of state
•
Beans relatively light-weight, but still heavy-
weight programming model
─
4 classes + deployment descriptor
─
Requires implementation of javax.ejb.EntityBean
─
Deployment descriptor
•
Can’t test logic outside the container
─
Abstract classes
─
CMRs
─
Create mechanisms, Home interface
•
Entities not serializable, so need DTOs
| 2004 JavaOne
SM
Conference | Session TS-2836
13
What’s Missing?
•
Lack of sufficient modeling capabilities
─
No polymorphism
─
No support for implementation inheritance
─
Lacks O/R mapping specification
•
Query language still missing some
important features
─
Projection
─
Subqueries
─
Outer joins
─
Dynamic queries
─
Additional functions, etc.
─
Provision for direct SQL queries
| 2004 JavaOne
SM
Conference | Session TS-2836
14
How Do We Improve It?
Goals of
EJB™
3.0 Architecture
Why We Need to Simplify Persistence
EJB™
3.0 Entity Bean Drill Down
Entity Bean Goals
Simplified Persistence Model
Query Language Enhancements
Summary and Current Status
Where to Get More Info at JavaOne
SM
Conference
| 2004 JavaOne
SM
Conference | Session TS-2836
15
EJB 3.0 Architecture’s Goals for CMP
•
Simplify programming model
─
Reduce number of programming artifacts
─
POJO/JavaBeans™ like other EJB™ 3.0 beans
─
Eliminate deployment descriptor from
developer’s view
•
Make instances usable outside the container
─
Facilitate testability
─
Remove need for data transfer objects (DTOs)
•
Support for lightweight domain modeling
─
Inheritance and polymorphism
─
Object/Relational mapping metadata
•
More complete query capabilities
| 2004 JavaOne
SM
Conference | Session TS-2836
16
How?
Obvious Choices:
1) Yet another persistence model?
or
2) Simplify and fix existing model?
| 2004 JavaOne
SM
Conference | Session TS-2836
17
Process We Went Through
•
Looked at technical options and functionality
•
Identified items that most needed to be fixed
─
Complexity
─
Lack of testability outside the container
─
Need for improved modeling and querying
capabilities
─
DTO issues
•
Identified what we needed to preserve
─
EJB™ QL + enhancement of it
─
Container’s ability to interpose and manage
─
Tx / security / caching / faulting control, ...
| 2004 JavaOne
SM
Conference | Session TS-2836
18
Process We Went Through (Cont.)
•
Examined functionality trade-offs
─
POJOs vs. interfaces
─
New vs. factories
─
CMRs vs. testability
─
Homes
•
Converged on self-consistent set
of functionality
─
Serious exercise in prioritization
─
Meant removing a few things we liked
•
Kept focus centered on core object/
relational mapping
─
Non-relational databases, etc. a non-issue
─
Relational-database centric
| 2004 JavaOne
SM
Conference | Session TS-2836
19
POJO Entity Beans
•
Concrete classes (no longer abstract)
•
No required bean interfaces
•
Support new()
•
Usable outside the EJB™ container
─
As detached entities
─
For testing of business logic
•
getter/setter methods
─
Can contain logic (for validation, transformation, etc.)
•
Collection interfaces for relationships
•
Entities are not remotable
•
No required callback interfaces
| 2004 JavaOne
SM
Conference | Session TS-2836
20
EntityManager
•
No required entity bean Homes
•
EntityManager serves as untyped “home”
─
Provides lifecycle operations
─
create()
─
remove()
─
merge()
─
Etc. (flush, refresh, evict...)
─
Factory for Query objects
•
Can wrapper EntityManager to provided
typed homes
─
Can also use metadata
| 2004 JavaOne
SM
Conference | Session TS-2836
21
Lifecycle Model for Entities
•
new()
─
Instance is not yet managed
•
create()
─
Instance becomes managed
•
remove()
─
Instance is removed
•
Detached instances
─
Instances existing outside of original transaction
context in which created/retrieved
─
Serialized to other tiers
─
merge() merges their state back into
persistence context
| 2004 JavaOne
SM
Conference | Session TS-2836
22
POJO Entity Beans
•
Lots of points of control
─
Over lifecycle
─
CASCADE capabilities (CREATE, REMOVE, ALL, ...)
─
Scope of persistence context
─
Fetch/faulting behavior
─
FETCH JOINS, O/R mapping metadata
─
Isolation semantics
─
Metadata
| 2004 JavaOne
SM
Conference | Session TS-2836
23
EJB™ 3.0 Architecture
Entity Bean Example
@Entity public class Customer {
private Long id;
private String name;
private Address address;
private HashSet orders = new HashSet();
@Id(generate=AUTO) public Long getID() {
return id;
}
protected void setID (Long id) {
this.id = id;
}
...
| 2004 JavaOne
SM
Conference | Session TS-2836
24
EJB™ 3.0 Architecture
Entity Bean Example (Cont.)
...
@OneToMany(cascade=ALL)
public Set<Order> getOrders() {
return orders;
}
public void setOrders(Set<Order> orders) {
this.orders = orders;
}
}
| 2004 JavaOne
SM
Conference | Session TS-2836
25
Client View
@Stateless public class OrderEntryBean {
private EntityManager em;
@Inject void
setEntityManager
(EntityManager em){
this.em = em;
}
public void enterOrder(int custID, Order
newOrder){
Customer c = em.find(“Customer”, custID);
c.getOrders().add(newOrder);
newOrder.setCustomer(c);
}
// other business methods
}
| 2004 JavaOne
SM
Conference | Session TS-2836
26
Object/Relational Mapping Approach
•
What do we mean by this?
Choice spectrum:
Database-centric approach
Object-centric approach
| 2004 JavaOne
SM
Conference | Session TS-2836
27
O/R Mapping Approach
•
Developer is aware of mapping between
database schema and object schema
─
At query language level
─
At object/data transfer and faulting level
•
Hooks provided over mapping between
relational database and set of Java™ instances
─
Semantically explicit approach
─
Programmer is in control
─
Classes are transparent; mapping is explicit
•
Points of control
─
Query language
─
Metadata
| 2004 JavaOne
SM
Conference | Session TS-2836
28
Application Developer’s Strategy
•
Construction and manipulation of
“persistence context”
─
Set of managed persistent instances used
by application within a particular scope
─
Application developer knows the needed
shape of this
•
Use queries to bring in data sets of interest
─
Finder/select queries
─
Report queries (projection)
─
Outer join queries control prefetch
•
Use metadata to control faulting patterns
for navigational access
| 2004 JavaOne
SM
Conference | Session TS-2836
29
Building Up the Persistence Context
•
Queries
─
Most efficient way to access relational data
─
EJB™ QL significantly enhanced
•
Outer Fetch Joins
─
Very useful for explicitly controlling data prefetch
─
Minimize database roundtrips
─
Programmer knows data access patterns
| 2004 JavaOne
SM
Conference | Session TS-2836
30
Example: Outer Fetch Join
SELECT c
FROM Customer c LEFT JOIN FETCH c.orders
WHERE c.state = 'CA'
| 2004 JavaOne
SM
Conference | Session TS-2836
31
Use Java™ Application Metadata
to Tune Access
•
Relationship fetching
─
FetchType
─
EAGER
─
LAZY
•
Optimistic locking support
─
@Version
─
@Timestamp
| 2004 JavaOne
SM
Conference | Session TS-2836
32
Mapping Classes to Tables
•
Use Java™ application metadata to
specify mapping
•
Support for usual inheritance strategies
─
Table per class hierarchy
─
Table per class
─
Joined subclass
•
Default type mappings defined by spec
•
Custom type mappings for finer control
and flexibility
| 2004 JavaOne
SM
Conference | Session TS-2836
33
Inheritance Mapping Example
@Entity
@Table(name=”CUST”)
@Inheritance(strategy=SINGLE_TABLE,
discriminatorType=STRING,
discriminatorValue=”CUST”)
public class Customer {...}
@Entity
@Inheritance(discriminatorValue=”VCUST”)
public class ValuedCustomer extends Customer{...}
| 2004 JavaOne
SM
Conference | Session TS-2836
34
Same Example, Using Defaults
@Entity
public class Customer {...}
@Entity
public class ValuedCustomer extends Customer {...}
| 2004 JavaOne
SM
Conference | Session TS-2836
35
Extended Persistence Context
•
Persistence context typically corresponds to a
single JTA transaction
•
Extended persistence context can span multiple
JTA transactions
─
Important use case: “Application transactions”
─
Preserves state across longer-lived client
interactions (especially from Web tier)
─
Stateful session beans a natural fit for maintaining
extended persistence context
─
Optimistic transactions
•
Avoids need for detach/reattach in co-located
scenarios
| 2004 JavaOne
SM
Conference | Session TS-2836
36
EJB™ QL Enhancements
•
Bulk update and delete operations
•
Projection list (SELECT clause)
•
Group by, Having
•
Subqueries (correlated and not)
•
Additional SQL functions
─
UPPER, LOWER, TRIM, CURRENT_DATE, ...
•
Dynamic queries
•
Polymorphic queries
•
Criteria queries probably in 3.1
| 2004 JavaOne
SM
Conference | Session TS-2836
37
Example: Bulk Update/Delete
DELETE
FROM Customer c
WHERE c.status = 'inactive'
UPDATE Customer c
SET c.status = 'outstanding'
WHERE c.balance < 10000
| 2004 JavaOne
SM
Conference | Session TS-2836
38
Example: Subqueries
SELECT goodCustomer
FROM Customer goodCustomer
WHERE goodCustomer.balance < (
SELECT avg(c.balance) FROM Customer c)
SELECT DISTINCT emp
FROM Employee emp
WHERE EXISTS (
SELECT spouseEmp
FROM Employee spouseEmp
WHERE spouseEmp = emp.spouse)
| 2004 JavaOne
SM
Conference | Session TS-2836
39
Example: Joins
SELECT i.category
FROM Item i JOIN i.bids b
WHERE b.amount > :amount
SELECT i
FROM Item i LEFT JOIN FETCH i.bids
WHERE i.category = 'paintings'
| 2004 JavaOne
SM
Conference | Session TS-2836
40
Example: Projection
SELECT c.id, c.status
FROM Customer c JOIN c.orders o
WHERE o.count > 100
SELECT new CustomerDetails(c.id, c.status,
o.count)
FROM Customer c JOIN c.orders o
WHERE o.count > :ordercount
| 2004 JavaOne
SM
Conference | Session TS-2836
41
Example: Group By/Having
SELECT cat.color, sum(cat.weight), count(cat)
FROM Cat cat
GROUP BY cat.color
HAVING cat.color in ('black', 'tabby')
SELECT new PetData(rat.color, sum(rat.weight),
count(rat))
FROM Rat rat
GROUP BY rat.color
HAVING rat.color in ('agouti', 'hooded')
| 2004 JavaOne
SM
Conference | Session TS-2836
42
Query API
public List findWithName (String name) {
return em.CreateQuery (
“SELECT c FROM Customer c” +
“WHERE c.name LIKE :custName”)
.setParameter(“custName”, name)
.setMaxResults(10)
.listResults();
}
| 2004 JavaOne
SM
Conference | Session TS-2836
43
Named Queries
@NamedQuery(
name=
“findCustomersByName”,
queryString=
“SELECT c FROM Customer c” +
“WHERE c.name LIKE :custName”
)
@Inject public EntityManager em;
...
List customers =
em.createNamedQuery(“findCustomersByName”)
.setParameter(“custName”, “Smith”)
.listResults();
| 2004 JavaOne
SM
Conference | Session TS-2836
44
SQL
•
Allow direct SQL over actual database schema
─
Very useful for some applications
─
Database portability overrated for some applications
•
Allow SQL query results to be mapped
into entity beans and/or instances of other
Java™ classes
| 2004 JavaOne
SM
Conference | Session TS-2836
45
•
POJO-centric view of entity beans
─
No Home interface
─
No Component interface
─
No requirement to implement javax.ejb.EntityBean
•
Enhanced modeling capabilities
─
Inheritance; polymorphism
─
Major query language additions
─
O/R mapping specification
•
Metadata is major enabling technology
•
Early draft specification now available
Summary and Status
| 2004 JavaOne
SM
Conference | Session TS-2836
46
Conclusion
•
Major simplifications to entity bean programming
model
•
Focus is squarely on providing solid
O/R mapping technology
| 2004 JavaOne
SM
Conference | Session TS-2836
47
For More Information
•
BOF 1864
─
Community Discussion of EJB™ 3.0 Architecture
─
Meet with members of the EJB™ 3.0 Expert Group
| 2004 JavaOne
SM
Conference | Session TS-2836
48
Q&A
java.sun.com/javaone/sf
| 2004 JavaOne
SM
Conference | Session TS-2836
49
Enterprise
JavaBeans
TM
(EJB™)
3.0 Architecture
Simplified Persistence
Linda DeMichiel
EJB™ Specification Lead
Sun Microsystems
java.sun.com/j2ee