The Business Tier of the Java EE Architecture

The Business Tier of the Java EE Architecture
The Business Tier
of the Java EE Architecture
Communication
Software
2009-2010
Authors:
Simon Pickin
Florina Almenárez Mendoza
Natividad Martínez Madrid
Address:
Departamento de Ingeniería Telemática
Universidad Carlos III de Madrid
Spain
Version:
1.0
Acknowledgements: Bill Burke, JBoss Group, Tal Cohen, IBM Haifa
© The Authors
1. Java Persistence:
Object-Relational Impedance Mismatch
and Object-Relational Mapping (ORM)
Communication
Software
2009-2010
© The Authors
2
1
The Persistence Layer
•
JDBC not enough for independence of DBMS
–
–
–
–
•
supposes RDBMS & SQL
even between different RDBMS, SQL used may vary
java developer may not know (or want to know) SQL
too low-level
Use of a persistence layer
–
–
–
–
object-oriented abstraction of database
part of business tier
between business logic and data tier
what form for the persistence layer?
Communication
Software
2009-2010
© The Authors
The Data Access Object (DAO)
Pattern
•
Data Access Object (DAO) pattern
– object that encapsulates database access
•
•
separates client interface from access mechanisms
provides generic API
– mentioned in Sun's “Core J2EE Patterns”
– similar to Fowler’s Table Data Gateway pattern
– often used together with DTO pattern
•
Data Transfer Object (DTO) pattern
– object that encapsulates database data
– similar to Sun's (but not Fowler’s) Value Object pattern
Communication
Software
2009-2010
© The Authors
2
DAO Layer Considerations
•
DAO layer of an application
– usually comprises many DAOs
– some of the DAOs may encapsulate
•
•
•
SQL joins
updates on multiple tables
DAO layer solution
– will be too heavy without some DAO code generation
•
unless application very simple
– metadata used for code-generation could be obtained from
•
•
•
developer-defined descriptor file
database schema
both
Communication
Software
2009-2010
© The Authors
DAO Implementation Strategies
(1/3)
•
Code each DAO class explicitly
– simplest but least flexible
– change of DBMS often
implementation
•
implies
change
of
DAO
Use a DAO factory
– Factory Method pattern (Gamma et al.)
– uni-class factories
•
create instances of a single DAO class
– multi-class factories
•
create instances of multiple DAO classes
Communication
Software
2009-2010
© The Authors
3
DAO Implementation Strategies
(2/3)
•
Use an abstract DAO factory
– Abstract Factory pattern (Gamma et al.)
– encapsulates set of DAO factories
•
one for each DBMS or DBMS type
– returns pointer to a DAO factory
•
each factory implements same abstract interface
– client creates DAOs via same abstract interface
•
whatever the DBMS or DBMS type
Communication
Software
2009-2010
© The Authors
DAO Implementation Strategies
(3/3)
•
Use Generic DAO classes
– handle different DBMS of same type
– data source dependent details loaded from config. file
•
•
e.g. RDBMS: all DBMS-dependent SQL in configuration file
Use abstract DAO factory and generic DAO classes
– returns pointer to a DAO factory
– client uses abstract interface...
•
covers different DBMS types
– ... to create generic DAOs
•
covers different DBMSs of a given type
Communication
Software
2009-2010
© The Authors
4
The Active Record Pattern
•
Active Record pattern
– can be viewed as pattern combining DAO and DTO
– data and behaviour
– "An object that wraps a row in a database table or view,
encapsulates the database access, and adds domain logic
on that data." Fowler
Communication
Software
2009-2010
© The Authors
Active Record of Ruby on Rails
•
Model part of Ruby-on-Rails MVC framework
•
Fowler’s Active Record pattern
– + inheritance + object associations.
•
•
former via use of Single Table Inheritance pattern
latter via a set of macros
•
CoC and DRY principles
•
Imposes
– some aspects of database schema
– some naming conventions
•
Following RoR restrictions/conventions
– very rapid development
Communication
Software
2009-2010
•
Not following RoR restrictions/conventions
– "derails" the rapid development
© The Authors
5
From Active Record to ORM
•
ORM can be viewed as active record, or similar, with
maximum code generation and support added for many of
following:
–
–
–
–
–
transactions
caching
relational integrity
some implicit persistence
mapping of relationships
–
flexible mapping between objects and table rows:
•
•
•
•
–
–
Communication
Software
2009-2010
object associations (1:1, 1:N, N:1, M:N) ↔ foreign key constraints
single object represents single row
multiple objects represent single row
single object represents multiple rows (SQL join)
inheritance relations between persistent objects
lazy loading
© The Authors
OR Impedence Mismatch
Overview (1/2)
•
Current situation
– programming languages, design languages:
•
usually OO
– database management systems (DBMS)
•
usually relational
=> many, many developments/applications use both
•
Conceptual basis
– object model:
•
•
identity, encapsulation of state + behaviour,
inheritance, polymorphism
– relational model
Communication
Software
2009-2010
•
•
relation, attribute, tuple,
relation value, relation variable
=> non-trivial mapping: object model ↔ relational model
© The Authors
6
OR Impedence Mismatch
Overview (2/2)
•
Possible solutions
1. Avoid the problem
•
•
•
•
use XML databases
use OO languages + OODBMS
use non-OO languages + RDBMS
use OO languages incorporating relational concepts + RDBMS
2. Manual mapping
•
hand-code SQL using relational-oriented tools
e.g. JDBC, ADO.NET
3. Use DAO layer
•
•
accept limitations while working to reduce them
know when to stop trying to reduce them!
4. Use ORM framework
•
•
Communication
Software
2009-2010
accept limitations while working to reduce them
know when to stop trying to reduce them!
5. Mix and match
•
e.g. DAO layer, part of which uses ORM
© The Authors
OR Impedence Mismatch Details
(1/9)
•
Management issues
– to what extent should type of application or chosen
application technology constrain the DB schema?
•
relational model may be used by multiple applications
– care also needed with database caching
– need to manage two separate but tightly-coupled models
•
•
•
different teams may be responsible for each model
evolution/refactoring difficulties
which model is to be considered primary?
Communication
Software
2009-2010
© The Authors
7
OR Impedence Mismatch Details
(2/9)
•
Associations (also called relationships)
–
associations can have following multiplicities
•
•
–
relational level cannot model:
•
•
–
object level: 1-1,1-N, N-1 and M-N; unidirectional & birectional
relational level: 1-1 and unidirectional N-1 associations only
(foreign keys cannot point to collections)
unidirectional 1-N associations
bidirectional N-1 associations
relational static model incomplete
•
•
associations at object level in fact map to keys+joins
to generate domain model from relational model
–
–
•
•
•
Communication
Software
2009-2010
–
one relation for each class (R1, R2) + join relation Rx
one N-1 association from Rx to R1
one M-1 association from Rx to R2
navigating M-N associations between persistent objects
•
© The Authors
information must be added
M-N associations map to:
performance implications
OR Impedence Mismatch Details
(3/9)
•
Inheritance
1. table-per-class (containing only fields specific to that subclass)
•
•
Fowler's Class Table Inheritance pattern
efficiency problems: e.g. querying value of class attribute involves
join on all relations that are mapped to a derived classes
2. table-per-concrete-class (usually same as table-per-leaf-class)
•
•
•
Fowler's Concrete Table Inheritance pattern
integrity problems, e.g, uniqueness of id defined in abstract class not
easily enforced across the set of relations that are mapped to
derived classes
not normalized
3. table-per-inheritance-hierarchy
Communication
Software
2009-2010
© The Authors
•
•
•
•
•
Fowler's Single Table Inheritance pattern
unlikely to be normalized
often needs discriminator field to identify mapped class
sparse table: many fields must by nullable
efficiency problems reduced if most fields inherited from base class
4. between options 1 and 3: table-per-class-family
8
OR Impedence Mismatch Details
(4/9)
•
Polymorphism
– inclusion polymorphism in OO languages:
•
•
•
mechanism allowing different types to expose different
behaviour through the same interface
uses inheritance
most common use: override superclass method in a
subclass (late binding)
– ORM context
•
can sometimes mimic method overriding
– depending on chosen inheritance mapping
Communication
Software
2009-2010
© The Authors
OR Impedence Mismatch Details
(5/9)
•
Identity
–
relational model
–
OO model
•
•
two entries are identical if their content is identical
two entries are identical if their object reference is identical
–
–
•
•
–
•
–
could spell trouble
solution?: import OO world into relational world
•
Communication
Software
2009-2010
often considered dubious practice from theoretical point of view
tuples are indistinguishable in any case
same entity queried twice, loaded into different object instances
•
–
c.f. difference between "==" and ".equals" in Java
most RDMBS permit duplicate tuples
add database-generated key field and create new value for each
object instance
may be impractical
interaction with concurrent access, caching, clustering,...
© The Authors
9
OR Impedence Mismatch Details
(6/9)
•
Composition
– usual understanding:
•
composite deleted → all components deleted
– OO model: no problem (garbage collection)
– relational model: must be explicit
•
composite relation is 1-N: problematic
– possibilities in relational model
•
•
use database triggers
maintain coherence at application level
Communication
Software
2009-2010
© The Authors
OR Impedence Mismatch Details
(7/9)
•
Containment
– containers
•
•
OO model: collections, lists, sets
relational model: only relations
– difficulty in modelling OO containers in relational model
– example: lists with duplicates, solutions:
•
•
many DBMS allow duplicates, even if theoretically dubious,
though not normalized
split over two or more tables to normalize
Communication
Software
2009-2010
© The Authors
10
OR Impedence Mismatch Details
(8/9)
•
Encapsulation
– OO encapsulation
•
•
access modifiers: private, protected, public
interfaces
– only relational equivalent: views
– some problems:
•
use of access modifiers:
– may make it difficult to access values in order to persist them
– consequence: access considerations may influence domain
model
•
use of OO encapsulation: to control access to data
– but databases often shared between applications
Communication
Software
2009-2010
© The Authors
OR Impedence Mismatch Details
(9/9)
•
Data retrieval mechanism
– query-by-example, query-by-API
– query-by-language
•
•
use of object query languages
Object Navigation and Loading
– OO world
•
cost of navigation is very low
– relational world
•
•
cost of navigation (joins, multiple queries) is high
particularly across a network
– Stategies to reduce costs:
Communication
Software
2009-2010
•
•
•
lazy/on-demand loading of objects linked to retrieved object
aggressive loading of objects linked to retrieved object
lazy/on-demand loading of attribute values
– allows query optimization at database communication level
© The Authors
11
Approaches to ORM (1/3)
•
Top-Down
– relational schema optimized for the domain model
– may involve generation of a database schema by ORM
framework
– schema oriented towards a single application
•
•
not easily used by other applications
integrity often enforced at application level
– often uses database-generated primary keys for all
relations
•
though most likely breaks normalization
– common for prototypes / proof of concept
Communication
Software
2009-2010
© The Authors
Approaches to ORM (2/3)
•
Bottom-Up
– domain model optimized for the relational schema
– may involve generation of application code from database
schema
– often uses a 1-1 mapping from tables to classes
•
what about inheritance and encapsulation?
– objects may lose their associations
•
navigation is via the relational model (inefficient)
– domain model produced not very understandable to nondevelopers
– relational schema not easily evolved
•
Communication
Software
2009-2010
code generation cannot generate complete application
– OR impedance mismatch simply moved up towards UI?
© The Authors
12
Approaches to ORM (3/3)
•
Meet-in-the-Middle
– domain model optimized for communication with nondevelopers
– relational schema optimized for reliability and efficiency
– most common approach
•
partly due to long life of database schemas
Communication
Software
2009-2010
© The Authors
Java Persistence Technologies
(1/7)
•
JDBC: 1997 (v1), 1998 (v2)
– based on Microsoft's ODBC
•
based, in turn, on X/Open's SQL CLI
– foundation: objects for
•
•
•
•
Communication
Software
2009-2010
connection
statement
result set
Toplink: 1995 (Smalltalk), 1997 (Java)
–
–
–
–
developed by Carleton University spin-off company
contained most features expected of modern ORM
TopLink Essentials: recent JPA implementation
(note that the JDK1 released in 1996)
© The Authors
13
Java Persistence Technologies
(2/7)
•
EJB: 1998 (v1), 2001 (v2)
– specification for enterprise components
– includes entity beans for persistence
•
•
•
bean-managed persistence (BMP)
container-managed persistence (CMP)
Differences EJB1 & EJB2 entity beans
– better support for relationships (1:1,1:N, M:N)
– advances in CMP
– introduction of local interfaces
•
for entity beans: facilitates Session Facade pattern
Communication
Software
2009-2010
© The Authors
Java Persistence Technologies
(3/7)
•
EJB entity beans CMP
– object-relational mapping (ORM)
– not use Plain Old Java Objects (POJOs); EJBs must
•
•
implement special interfaces
extend special classes
– heavyweight and verbose
– classes automatically persistent
– persistent objects cannot execute outside EJB container
•
unit testing difficult
– object-relational mapping not fully specified
•
details left to container implementor
– defines an object query language (EJBQL)
Communication
Software
2009-2010
© The Authors
14
Java Persistence Technologies
(4/7)
•
Hibernate: 2002 (v1.0)
– open source product
– object relational mapping
•
–
–
–
–
–
sometimes used together with DAO layer or generic DAOs
lightweight
uses POJOs
persistent objects can execute outside an EJB container
object-relational mapping fully specified
to make classes persistent
•
explicitly invoke methods on a persistence manager
– defines an object query language (HQL)
– uses JDBC
– Hibernate Annotations + Hibernate EntityManager
Communication
Software
2009-2010
•
provides JPA implementation on top of Hibernate Core
© The Authors
Java Persistence Technologies
(5/7)
•
iBatis: 2003 (v1.0)
– open source product (now Apache)
– lightweight
– basically, a DAO layer
•
with support for transactions and inheritance
– all SQL externalised to XML files (called SQLMaps)
– objects persisted and queried are Java Beans
– POJOs can be mapped to input parameters of an SQL
statement or to results of executing an SQL query
– uses JDBC
Communication
Software
2009-2010
© The Authors
15
Java Persistence Technologies
(6/7)
•
Java Data Objects: 2002 (v1.0)
–
–
–
–
–
–
specification for persistable objects
inspiration from OODBMS, in particular, ODMG specs.
general object-data source mapping, not just ORM
support for transactions, caching, associations, inheritance
uses POJOs
to make classes persistent
•
explicitly invoke method on a persistence manager
– defines an object query language (JDOQL)
– usually implemented via JDBC
Communication
Software
2009-2010
© The Authors
Java Persistence Technologies
(7/7)
•
JPA (2006)
–
–
–
–
–
–
–
–
part of EJB3 spec. but can be used independently
inspiration in Hibernate, TopLink, JDO,…
specification for flexible object-relational mapping
lightweight
uses POJOs
persistent objects can execute outside an EJB container
object-relational mapping fully specified
to make classes persistent
•
explicitly invoke an Entity Manager
– defines an object query language (JPQL)
– alternative to deployment descriptors: Java annotations
Communication
Software
2009-2010
© The Authors
16
Bibliography for Section 1
•
Persistence in the Enterprise: A Guide to Persistence Technologies. Roland
Barcia, Geoffrey Hambrick, Kyle Brown, Robert Peterson and Kulvir Singh
Bhogal. IBM Press, 2008
•
Patterns of Enterprise Application Architectures. Martin Fowler. AddisonWesley 2002. Summary available at:
http://my.safaribooksonline.com/9780768680591
http://martinfowler.com/eaaCatalog/
•
J2EE Patterns
•
The Object-Relational Impedance Mismatch. Scott Ambler.
http://java.sun.com/blueprints/patterns/
http://www.agiledata.org/essays/mappingObjects.html
•
The Vietnam of Computer Science. Ted Neward
http://blogs.tedneward.com/2006/06/26/The+Vietnam+Of+Computer+Scie
nce.aspx
•
Object-Relational Mapping as a Persistence Strategy. Douglas Minnaar.
http://www.eggheadcafe.com/tutorials/aspnet/e957c6de-8400-4748b42d-027f7a228063/objectrelational-mapping.aspx
Communication
Software
2009-2010
•
Object Relational Mapping Strategies. ObjectMatter.
http://www.objectmatter.com/vbsf/docs/maptool/ormapping.html
© The Authors
2. Java Persistence:
the Java Persistence API (JPA)
Communication
Software
2009-2010
© The Authors
34
17
Entities
•
Entity
–
–
–
•
grouping of state treated as single unit
can be made persistent
normally only created, deleted & updated within a transaction
JPA entity
–
fine-grained POJO with following restrictions
•
•
public or protected, no-argument constructor
persistent fields are private, protected, or package-private
•
neither class nor its methods nor its fields are final
–
–
–
normally stored in a single place
detachable from / attachable to persistence layer
•
•
•
Communication
Software
2009-2010
clients access state via accessor or business methods
attached: has persistent identity, unique in persistence context
detached: can be passed by value to other JVM (if serializable)
so also serve as data transfer objects
© The Authors
Entity Metadata
•
JPA entities have associated metadata
–
–
enabling persistence layer to recognize & manage entity
specified either using Java annotations or as XML
–
“annotation parameters” give more info about annotations
•
•
•
•
JPA defines default values for many annotations
•
•
–
particularly element specifications
“configuration by exception”
ease-of-use (especially first use)
•
•
annotation parameters called elements
expressions element=value called element specifications
Default metadata
–
Communication
Software
2009-2010
annotations easier
c.f. CoC principle of Ruby on Rails
Java EE container
–
web container + EJB container + persistence provider
© The Authors
18
Managing Entities
•
Entities are managed by an entity manager
–
–
each entity manager is associated with a persistence context
persistence context:
•
•
The EntityManager API
–
–
–
creates and removes persistent entity instances
finds entities by the entity’s primary key
allows queries to be run on entities
–
detaches entities from / re-attaches entities to persistent storage
•
•
uses the Java Persistence Query Language (JPQL)
Entity managers may be
–
–
Communication
Software
2009-2010
set of managed entity instances that exist in a particular data store
container-managed
application-managed
differ in transactional behaviour & life-cycle management
© The Authors
Persistence Units
•
A persistence unit
– represents the data contained in a single data store
– has associated EntityManagerFactory
•
•
create entity manager instances with given configuration
A persistence unit comprises
– a collection of entities that are managed together
•
i.e. a set of entity classes
– the corresponding configuration information
•
•
Communication
Software
2009-2010
e.g. persistence provider, data source
File persistence.xml:
– contains the definition of one or more persistence units
– JPA inside a Java EE container
•
many more things to define in persistence.xml file
© The Authors
19
Defining a JPA Entity
•
An entity is a class that:
–
–
satisfies restrictions mentioned above
is annotated with @Entity
–
uses one of the following to denote the primary key:
•
•
–
if primary key auto-generated
–
if primary key composite
•
•
•
Communication
Software
2009-2010
an attribute annotated with @Id
a mutator method (getXxx) annotated with @Id
annotate also with @GeneratedValue + element spec
annotate with @EmbeddedId or @IdClass instead of @Id
Defaults element values defined for the @Entity annotation:
–
–
–
entity mapped to relation of same name
all attributes of entity persistent
each entity attribute mapped to relation attribute of same name
can be overridden (by using element specifications)
© The Authors
The Query Interface
• Method find() used to find single entity by primary key
– more complicated search needs Query inteface
– same interface used for bulk updates and deletes (new to EJB3)
• To obtain an object implementing the Query interface:
– two entity manager methods for dynamic queries
public Query createQuery(String jpqlString)
public Query createNativeQuery(String sqlString)
– one entity manager method (with 3 variants) for static queries
public Query createNamedQuery(String sqlOrJpqlString)
• Main methods on the Query interface
Communication
Software
2009-2010
public
public
public
public
public
public
Public
List getResultList()
Object getSingleResult()
int executeUpdate() // bulk update or delete
Query setMaxResults(int maxResult)
Query setFirstResult(int startPosition)
Query setParameter(String name Object value)
Query setFlushMode(FlushModetype flushMode)
© The Authors
20
The Java Persistence Query
Language
•
Similar to SQL:
–
–
–
SELECT FROM WHERE, GROUP BY, HAVING, ORDER BY
UPDATE SET WHERE
DELETE FROM WHERE
and even more similar to HQL (Hibernate Query Language)
•
Subqueries allowed in WHERE and HAVING clauses
•
Set functions for use in grouping / aggregate queries
–
•
AVG, COUNT, MAX, MIN, SUM
Navigation through entity graphs
– using path expressions (dot notation)
•
allowed in SELECT, SET, FROM, WHERE clauses
– though illegal for path expressions to navigate beyond
•
•
Communication
Software
2009-2010
collection-valued relationship attribute
persistent attribute
© The Authors
Example 1: Simple CRUD (1/3)
// source: Pro EJB3, Java Persistence API. M. Keith, M. Schincariol
@Entity
public class Employee {
@Id private int id;
private String name;
private long salary;
public Employee(){}
public Employee(int id) {this.id = id;}
public
public
public
public
public
public
int getId() {return id;}
void setId(int id) {this.id = id;}
String getName() {return name;}
void setName(String name) {this.name = name;}
long getSalary() {return salary;}
void setSalary(long salary) {this.salary = salary;}
}
Communication
Software
2009-2010
© The Authors
21
Example 1: Simple CRUD (2/3)
import javax.persistence.*;
import java.util.Collection;
public class EmployeeService {
protected EntityManager em;
public EmployeeService(EntityManager em) {
this.em = em;
}
public Employee createEmployee(int id, String name, long salary) {
Employee emp = new Employee(id);
emp.setName(name);
emp.setSalary(salary);
em.persist(emp);
return emp;
}
public Employee findEmployee(int id) {
return em.find(Employee.class, id);
}
Communication
Software
2009-2010
© The Authors
Example 1: Simple CRUD (3/3)
public RemoveEmployee(int id) {
Employee.emp = findEmployee(id);
if (emp != null){
em.remove(emp);
};
}
// entity is managed so change made to persistent representation
public raiseEmployeeSalary (int id, long raise) {
Employee.emp = findEmployee(id);
if (emp != null){
emp.setSalary(emp.getSalary()+ raise);
};
return emp;
}
Communication
Software
2009-2010
public Collection<Employee> findAllEmployees() {
Query query = em.createQuery("SELECT e FROM Employee e");
return (Collection<Employee>) query.getResultList();
}
}
© The Authors
22
ORM: Entities and Simple
Attributes
•
•
Entity class ↔ table:
–
–
default: table name = unqualified name of entity class
if other mapping required: use @Table(name="...")
–
mapping a class to multiple tables:
• use annotations @SecondaryTables & @SecondaryTable
Entity attribute whose value is a simple type ↔ column:
–
notes regarding simple types:
•
•
•
–
default: attribute is persistent and column name = attribute name
–
if other mapping required: use @Column(name="...")
•
Communication
Software
2009-2010
primitive types, wrapper classes of primitive types, Strings, temporal
types, enumerated types, serializable objects,…
can be denoted explicitly with @Basic but not necessary unless
adding elements, e.g. @Basic(fetch=FetchType.LAZY)
set of allowable types for primary key (recall denoted with @Id or
@EmbeddedId / @IdClass) is subset of simple types
not persistent: use transient modifier or @Transient annotation
© The Authors
Example 2: Single-Table
Mapping
//
// source:
source: JBoss
JBoss EJB3
EJB3 tutorial,
tutorial, B.
B. Burke
Burke
@Entity
@Entity
@Table(name=“AUCTION_ITEM”)
@Table(name=“AUCTION_ITEM”)
public
public class
class Item
Item {{
private
private long
long id;
id;
private
private String
String description;
description;
private
private String
String productName;
productName;
private
private Set<Bid>
Set<Bid> bids
bids == new
new HashSet();
HashSet();
private
User
seller;
private User seller;
create
create table
table AUCTION_ITEM
AUCTION_ITEM
((
ITEM_ID
Number,
ITEM_ID Number,
DESC
DESC varchar(255),
varchar(255),
ProductName
ProductName varchar(255),
varchar(255),
USER_ID
USER_ID Number
Number
);
);
@Id(generate=GeneratorType.AUTO)
@Id(generate=GeneratorType.AUTO)
@Column(name=“ITEM_ID”)
@Column(name=“ITEM_ID”)
public
public long
long getId()
getId() {{
return
return id;
id;
}}
public
public void
void setId(long
setId(long id)
id) {{
this.id
this.id == id;
id;
}}
….
….
Communication
Software
2009-2010
}}
© The Authors
23
Example 2: Multi-Table Mapping
(1/2)
//
// source:
source: JBoss
JBoss EJB3
EJB3 tutorial,
tutorial, B.
B. Burke
Burke
@Entity
@Entity
@Table(name=“OWNER”)
@Table(name=“OWNER”)
@SecondaryTable(name=“ADDRESS”,
@SecondaryTable(name=“ADDRESS”,
pkJoinColumns={
pkJoinColumns={
@PrimaryKeyJoinColumn(name=“ADDR_ID”,
@PrimaryKeyJoinColumn(name=“ADDR_ID”,
referencedColumnName=“ADDR_ID”})
referencedColumnName=“ADDR_ID”})
public
public class
class Owner
Owner {{
private
private long
long id;
id;
private
private String
String name;
name;
private
String
private String street;
street;
private
private String
String city;
city;
private
private String
String state;
state;
Communication
Software
2009-2010
@Id(generate=GeneratorType.AUTO)
@Id(generate=GeneratorType.AUTO)
@Column(name=“OWNER_ID”)
@Column(name=“OWNER_ID”)
public
public long
long getId()
getId() {{
return
return id;
id;
}}
public
public void
void setId(long
setId(long id)
id) {{
this.id
this.id == id;
id;
}}
create
create table
table OWNER
OWNER
((
OWNER_ID
OWNER_ID Number,
Number,
NAME
NAME varchar(255),
varchar(255),
ADDR_ID
ADDR_ID Number,
Number,
);
);
create
create table
table ADDRESS
ADDRESS
((
ADDR_ID
Number,
ADDR_ID Number,
STREET
STREET varchar(255),
varchar(255),
CITY
CITY varchar(255),
varchar(255),
STATE
STATE varchar(255)
varchar(255)
);
);
© The Authors
Example 2: Multi-Table Mapping
(2/2)
……
@Column(name=“STREET”,
@Column(name=“STREET”,
secondaryTable=“ADDRESS”)
secondaryTable=“ADDRESS”)
public
public String
String getStreet()
getStreet() {{
return
return street;
street;
}}
public
public void
void setStreet(String
setStreet(String street)
street) {{
this.street
this.street == street;
street;
}}
@Column(name=“CITY”,
@Column(name=“CITY”,
secondaryTable=“ADDRESS”)
secondaryTable=“ADDRESS”)
public
public String
String getCity()
getCity() {{
return
return city;
city;
}}
protected
protected void
void setCity(String
setCity(String city)
city) {{
this.city
this.city == city;
city;
}}
Communication
Software
2009-2010
create
create table
table OWNER
OWNER
((
OWNER_ID
Number,
OWNER_ID Number,
NAME
NAME varchar(255),
varchar(255),
);
);
create
create table
table ADDRESS
ADDRESS
((
ADDR_ID
Number,
ADDR_ID Number,
STREET
STREET varchar(255),
varchar(255),
CITY
CITY varchar(255),
varchar(255),
STATE
varchar(255)
STATE varchar(255)
);
);
……
© The Authors
24
Constraints on Schema
Generation
• To specify unique constraints
– use unique element of @Column & @JoinColumn
– use uniqueConstraints element of @Table & @SecondaryTable
• To specify not-null constraint
– use nullable element of @Column & @JoinColumn
• To specify string-length constraints
– use length element of @Column (no such element in @JoinColumn)
– default is 255
• To specify floating-point constraints
– use precision and scale elements of @Column (not @JoinColumn)
• To specify a particular SQL DDL string for a column
– Use
columnDefinition element of @Column,
@PrimaryKeyJoinColumn, @DiscriminatorColumn
Communication
Software
2009-2010
@JoinColumn,
© The Authors
ORM: Relationships (1/2)
•
Entity attribute whose value is another entity
–
can be annotated with one of the following multiplicities:
•
•
•
•
–
•
Communication
Software
2009-2010
•
@OneToOne
@OneToMany
@ManyToOne
@ManyToMany
foreign key denoted with @JoinColumn(name="...")
Every association/relationship is said to have an “owning side”
–
a bidirectional association is also said to have an “inverse side”
–
OneToMany & ManyToOne: owner must be many side
–
OneToOne: owner must be side that contains foreign key
–
inverse side uses mappedBy element of multiplicities annotation
to identify corresponding attribute on owning side
Composition relations denoted using the element spec.:
–
cascade=REMOVE on the inverse side
© The Authors
25
ORM: Relationships (2/2)
• Join table required for
– many-to-many relations
– unidirectional one-to-many relations
– Example (bidirectional many to many):
@Entity
Public class Employee
@Id private ind id;
Private String name;
@ManyToMany // inverse side has @ManyToMany(mappedBy="projects")
@JoinTable(name="EMP_PROJ", // annotation on owning side only
[email protected](name="EMP_ID"),
[email protected](name="PROJ_ID"))
Private Collection<Project> projects;
• Join column
– to owning side described in joinColumns element
– to inverse side described in inverseJoinColumns element
– default names used if not specified (also for join table)
Communication
Software
2009-2010
© The Authors
ORM: Inheritance
•
Base class of inheritance hierarchy can be annotated via:
–
@Inheritance(InheritanceType=X)
where X is one of the following (default is 1)
1. SINGLE_TABLE: Single Table Inheritance pattern
2. JOINED: Class Table Inheritance pattern
3. TABLE_PER_CLASS: Concrete Table Inheritance pattern
•
2 & 3: hierarchy may contain classes that are not persistable
–
•
“transient classes” (non-entities) or “mapped superclasses”.
SINGLE_TABLE and sometimes JOINED inheritance
– base clase has @DiscriminatorColumn annotation
•
–
Communication
Software
2009-2010
•
elements specify properties of the discriminator column, e.g. type
each concrete entity uses @DiscriminatorValue annotation
Queries on class hierarchy are polymorphic
© The Authors
26
Database Synchronisation
• Database writes queued until EntityManager synchronises
– calls to EntityManager methods persist(), merge(), remove()
– not coordinated with updates / deletes sent via Query interface
• Writes flushed to database according to one of policies:
– when a transaction commits
javax.persistence.FlushModeType = COMMIT
– before a query concerning this data is executed
javax.persistence.FlushModeType = AUTO
• Explicit management of flushing:
– to find out / change flushing policy
EntityManager.getFlushMode()
EntityManager.setFlushMode(FlushModeType flushMode)
Query.setFlushMode(FlushModeType flushMode)
Communication
Software
2009-2010
– to flush changes to database explicitly
EntityManager.flush() (c.f. also EntityManager.refresh())
© The Authors
Database Locking
• Default locking policy: optimistic concurrency control
– at transaction commit
• if data changed with respect to in-memory version: rollback
• if not, go ahead with the commit
– based on use of a version field
• entity field annotated with @Version
• version number checked to detect changes
• Other possibilities
– set isolation level globally (see transactions section)
– method EntityManager.lock(), pass entity as parameter
• read lock: parameter LockModeType.READ
– a transaction update may fail if other transaction has a read lock
• write lock: parameter LockModeType.WRITE
Communication
Software
2009-2010
– forces increments of version field whether entity updated or not
© The Authors
27
Life-Cycle Call-Back Methods
• Methods called by persistence provider
– entity optionally registers for call-back on life-cycle events
• by annotating methods of bean class
– restrictions on method that can be life-cycle call-back:
• has no arguments, returns void, doesn’t throw application exceptions
– may be placed in a separate listener class
• declared via annotation @EntityListener
• Possible entity life-cycle call-back methods
– method annotated @PrePersist / @PostPersist
• called before/after executing EntityManager.persist()
– method annotated @PreRemove / @PostRemove
• called before/after executing EntityManager.remove()
– method annotated @PreUpdate / @PostUpdate
• called before/after database synchronization
Communication
Software
2009-2010
– method annotated @PostLoad
• called after instance loaded via EM find() or getReference()
© The Authors
Entity Life-Cycle
Source: Pro EJB3. Java Persistence API. Mike Keith et al
•
Transactional persistence context
– persistence context ends when transaction ends
Communication
Software
2009-2010
•
Extended persistence context
– persistence context ends when caller is destroyed
© The Authors
28
Resource-Local Transactions in
JPA
•
Entities can be used inside resource-local transactions
– transactions completely under control of the application
– via EntityTransaction interface
•
The EntityTransaction interface
– similar to JTA UserTransaction interface (see later)
begin,
commit,
rollback,
isActive,
– operations:
setRollbackOnly, getRollbackOnly,
– operations implemented via JDBC Connection transaction methods
– obtained by EntityManager.getTransaction()
•
Not generally used when in Java EE environment
– JTA transactions recommended instead (see later)
Communication
Software
2009-2010
© The Authors
Inversion of Control (IoC)
•
Inversion of control (IoC) refers to situation where
– an external system calls your code
– rather than your code calling the external system
•
Sometimes referred to as the 'Hollywood principle':
– "don't call us, we'll call you".
•
Example: EJB callback methods
Communication
Software
2009-2010
© The Authors
29
Dependency Injection (DI) (1/2)
•
To obtain a given service, components often need to know:
–
–
–
•
which other components they need to communicate with
where to locate them
how to communicate with them
Naive approach
–
–
embed service location / instantiation logic in code of its clients
problems with naive approach:
•
•
•
Dependency injection (DI) approach
–
–
clients declare their dependency on the services
“external code” injects the service
•
Communication
Software
2009-2010
changes in service access imply changes in code of many clients
difficult to unit test client components without using real service
–
i.e. assumes responsibility for locating and instantiating the
services and then supplies the service reference
“external code”: often DI container / DI framework
© The Authors
Dependency Injection (DI) (2/2)
•
Dependency injection
–
–
–
is a particular form of IoC
ensures that configuration of services is separated from their use
dependencies configured externally in one place
•
•
Externalising service-access dependency makes code
–
–
–
•
Communication
Software
2009-2010
for multiple clients
more reusable
more testable: easy to inject dependency on mock service
more readable
Ways of carrying out dependency injection
–
–
–
constructor injection
setter injection
interface injection
© The Authors
30
Example: Dependency Injection
(1/3)
•
Obtaining application-managed entity manager, Java SE
– using Persistence class, no dependency injection
// source: Pro EJB3, Java Persistence API. M. Keith, M. Schincariol
public class EmployeeClient {
public static void main(String[] args) {
EntityManagerFactory emf
= Persistence.createEntityManagerFactory("EmployeeService");
EntityManager em = emf.CreateEntityManager();
Collection emps
= em.CreateQuery("SELECT e FROM Employee e").getResultList();
for(Iterator I = emps.iterator(); i.hasNext();){
Employee e = (Employee) i.next();
System.out.println(e.getId() + ", " + e.getName());
}
em.close();
emf.close();
Communication
Software
2009-2010
}
© The Authors
Example: Dependency Injection
(2/3)
• Obtaining application-managed entity manager, Java EE
– injection of Persistence Unit to obtain EntityManagerFactory
– Java EE container peforms the injection
Communication
Software
2009-2010
// source: Pro EJB3, Java Persistence API. M. Keith, M. Schincariol
public class LoginServlet extends HttpServlet {
@PersistenceUnit(unitName="EmployeeService")
EntityManagerFactory emf;
protected void doPost(HttpServletRequest request,
HttpServletResponse response){
String userId = request.getParameter("user")
// check valid user
EntityManager em = emf.createEntityManager();
try{
User user = user.find(User.class, userId);
if (user == null) {
// return error page...
}
} finally {em.close();}
// ...
}
}
© The Authors
31
Example: Dependency Injection
(3/3)
• Obtaining container-managed entity manager, Java EE
– injection of Persistence Context to obtain EntityManager
– Java EE container peforms the injection
– explanation of @stateless annotation: see later
// source: Pro EJB3, Java Persistence API. M. Keith, M. Schincariol
@Stateless
public class ProjectServiceBean implements ProjectService {
@PersistenceContext(unitName="EmployeeService")
EntityManager em;
public void assignEmployeeToProject(int empId, int projectId) {
Project project = em.find(Project.class, projectId);
Employee employee = em.find(Employee.class, empId);
project.getEmployees().add(employee);
employee.getProjects().add(project);
}
// ...
Communication
Software
2009-2010
}
© The Authors
Bibliography for Section 2
•
Pro EJB3. Java Persistence API. Mike Keith and Merrick Schincariol.
Apress, 2006
http://books.google.com/books?id=fVCuB_Xq3pAC
•
The Java Persistence API. Sun Microsystems
•
The Java EE 5 Tutorial. Part V: Persistence. Sun Microsystems
http://java.sun.com/javaee/technologies/persistence.jsp
http://java.sun.com/javaee/5/docs/tutorial/doc/bnbpy.html
•
Inversion of Control Containers and the Dependency Injection pattern. Martin
Fowler, 2004
http://www.martinfowler.com/articles/injection.html
Communication
Software
2009-2010
© The Authors
32
3. Enterprise JavaBeans 3.0
Communication
Software
2009-2010
65
© The Authors
Introduction
• The business tier implements the business logic
– that is, the core functionality of an enterprise application
• Enterprise JavaBeans (EJB) is a complete specification of a
service component architecture
– execute business logic
– access databases
– integrate with other systems
• Advantages of EJBs:
– developer concentrates on the business logic and uses the
services provided by the container
• transactions, security, life-cycle management, multi-threading,
connection pooling, etc.
Communication
Software
2009-2010
© The Authors
– components: reuse y abstraction
– compatible with other Java APIs
66
33
EJB Container Services (1/5)
Container: execution environment for installed EJB components
• Transaction management:
– sequence of actions (& data accesses) executed “atomically”
• ACID (Atomic, Consistent, Isolated, Durable)
• avoids problems that can arise from concurrent access to data
• whole sequence can be undone (“rolled back”) in case of failure
– container provides transaction-handling protocols
• e.g. two-phase commit protocol
– bean-managed transactions (BMT)
• bean developer explicitly codes transaction start, termination,
rollback, etc. using JTA (Java Transaction API)
– container-managed transactions (CMT)
Communication
Software
2009-2010
• bean developer doesn’t explicitly code transactions
• the methods that must execute in a transaction are specified with
annotations or in the deployment descriptor XML file
67
© The Authors
EJB Container Services (2/5)
• Resource and life-cycle management:
– resources: threads, sockets, database connections,…
– life-cycle: create & destroy instances, activate & passivate
instances,…
– exact life-cycle states and processes depend on type of bean
• Remote accessibility / distributed objects:
– bean developer doesn’t explicitly code remote accessibility
– EJB server provides communication protocols to access
distributed remote objects
• must support RMI-IIOP (c.f. CORBA spec.) and SOAP 1.2 (via JAXWS API or older JAX-RPC API)
• may also support other communication protocols
– container implements distributed calls using communication
infrastructure
Communication
Software
2009-2010
© The Authors
• e.g. generates stubs and skeletons
68
34
EJB Container Services (3/5)
• Security:
– authentication
• validation of user’s identity
– authorisation (of access to components)
• security policy specifying what user can and cannot do
• declarative concept based on user “roles”:
• roles and their access rights to business methods defined with
annotations or in deployment descriptor XML file
• deployer assigns roles to users
– EJB server manages users and roles
– container deals with access control
– secure communications
• Concurrency (“multi-threading”)
– bean developer doesn’t explicitly code multithreading
– e.g. two ways of handling concurrent requests
Communication
Software
2009-2010
• maintain instance pool & direct requests to bean instances from pool
• serialize requests to a single bean instance
69
© The Authors
EJB Container Services (4/5)
• Naming and directory service:
– association of names to object references in hierarchical directory
structure
• JNDI (Java Naming and Directory Interface) API:
– Environment Naming Context of a bean:
• JNDI namespace (private directory) specific to each bean class
• for accessing properties, resources, other beans from container
• referenced from within a bean via name java:comp/env
• Messaging:
– container provides access to messaging service
• JMS (Java Messaging Service) API
– asynchronous communication between 2 or more participants
•
through a message-queueing system
– receivers of messages must be message-driven beans
Communication
Software
2009-2010
© The Authors
• any enterprise bean can be an emitter of messages
70
35
EJB Container Services (5/5)
• Timer / scheduling
– schedule notifications to be sent to EJBs at specific times
– c.f. Unix cron
• Persistence (EJB2):
– EJB 2.1 entity beans can be used as alternative to JTA entities
• EJB3 container must support EJB2.1 entity beans
– instances of entity beans in memory linked to business data
• container guarantees data consistency (periodic loading and storing)
– bean-managed persistence (BMP)
• bean developer codes DB access explicitly using JDBC but container
decides when to call this code
• bean instance uses JDBC connections provided by the container
– container-managed persistence (CMP)
Communication
Software
2009-2010
© The Authors
• bean developer doesn’t code DB access explicitly
• generally supports connection to relational databases
• exact means of persistence depends on the container and is
independent of the bean
71
Modelling Enterprise Applications
• Enterprise applications are organised in components that
implement business entities or business processes
– business entities represent enterprise info
– business processes represent manipulation of this info
Communication
Software
2009-2010
© The Authors
72
36
Business Entities
• Business entities are business objects:
– represent information maintained by the company
– have persistent state (typically maintained in database)
• Examples:
– client, order, account, employee,...
• May have associated “business rules”:
– constraining values of entity state
• e.g. post codes have 5 digits (in Spain, at least!)
– maintaining relations between entities
• e.g. relating a customer to several orders
Communication
Software
2009-2010
73
© The Authors
Business Processes
• Business objects that encapsulate an interaction
between a user and a business entity
– update state of business entities
– maintain unique identity throughout life-cycle
• May have own state
– persistent state: process divided into stages and may
involve multiple actors: collaborative business process
• example: processing a loan request
– transitory state: process completed in one conversation
with one actor: conversational business process
• example: taking money out of a cashpoint (US english: ATM)
Communication
Software
2009-2010
© The Authors
74
37
Business Rules
• Distributed among the components that implement
the business entities and processes
– according to whether rule applies to entity or process
• Examples:
– entity:
the balance of an account cannot be negative
(independent of the process that causes it to occur)
– process:
the max amount that can be withdrawn from a cashpoint is 500€
(independent of the state of the account entity)
Communication
Software
2009-2010
75
© The Authors
Enterprise JavaBeans
• Session Beans:
– processes executed in response to a client request (e.g. bank
transactions, calculations, implementation of orders,…)
– collaborative process: make use of JPA entities / entity beans
– receive synchronous calls to methods defined on business interface
• JPA Entites (EJB3) / Entity Beans (EJB2):
– persistent objects associated to data
• e.g. bank account, product order,...
– passive information support via methods for operations on data
– receive synchronous calls to methods defined on business interface
• Message-Driven Beans:
Communication
Software
2009-2010
© The Authors
– processes executed as a response to the reception of a message
– receive asynchronous calls via a channel
76
38
JPA Entities (EJB3) / Entity Beans
(EJB 2.x)
• Model concepts / business objets with persistent state
– for example, data in the database
• Can be used by various clients jointly & simultaneously
• Externally-visible identity: primary key
– instance can be accessed by other programs
• Long lived (lifetime that of associated data)
– persistent state typically changes transactionally
– state survives restart of container, server or computer
• Entity beans only: persistence may be bean-managed or
container-managed (difference not visible to the client)
Communication
Software
2009-2010
• JPA entities only: can be detached from and re-attached to
(merged with) persistence layer
77
© The Authors
Message-driven Beans
• Message-driven beans are receivers of messages
• Use a messaging service
– intermediary between emitter and message-driven bean
– incoming messages captured by container and redirected to bean
instance
– publisher-subscriber pattern:
emitter & receiver (message-driven bean) mutually anonymous
• Asynchronous communication
– session y entity beans: (blocking) synchronous method calls
• Message-driven Beans have no identity
– like stateless session beans:
cannot maintain information about the state of the emitter
Communication
Software
2009-2010
© The Authors
78
39
Session Beans
• Session bean basic life-cycle
– instance created/bound when client calls bean
• associated to client as private resource for duration of client process
– instance deleted/released when client process finishes
• Stateless session beans:
– client process involves a single invocation
– don’t store client-specific data between invocations
• use data passed as parameters or obtained from database
– all instances have same identity
• “Stateful” session beans:
– client process involves multiple invocations
– maintain client state across multiple invocations
• client-dependent state called conversational state
Communication
Software
2009-2010
– state not persistent: lost when client releases bean
– each instance has different identity
79
© The Authors
Session beans, client view
• The so-called “business interface”
– is a POJI (Plain Old Java Interface)
– declares methods that can be called by bean clients
– can be declared as local via annotation @Local
• can then be accessed by other beans in the same EJB container
– can be declared as remote via annotation @Remote
• can then be accessed by applications outside the EJB container
• no need to declare RMI remote exceptions
– can be generated from bean class by container
• if all bean class methods are to be available to clients
• When bean client invokes business interface method
Communication
Software
2009-2010
© The Authors
– interaction is with proxy stub, not with bean class IMPORTANT!
– proxy stub routes invocation and reply via container
– container injects middleware services based on bean metadata
• metadata specified as annotations or in XML deployment descriptor
80
40
Example 3: Stateless Session
Bean, v1
package examples.session.stateless;
// This is the Hello business interface
public interface Hello {
public String hello();
}
package examples.session.stateless;
import javax.ejb.Remote;
import javax.ejb.Stateless;
Communication
Software
2009-2010
© The Authors
// Stateless session bean
@Stateless
@Remote(Hello.class)
public class HelloBean implements Hello {
public String hello() {
return "Hello, World";
}
}
81
Example 3: Stateless Session
Bean, v2
package examples.session.stateless;
// This is the Hello business interface
@Remote public interface Hello {
public String hello();
}
package examples.session.stateless;
import javax.ejb.Remote;
import javax.ejb.Stateless;
Communication
Software
2009-2010
© The Authors
// Stateless session bean
@Stateless
public class HelloBean implements Hello {
public String hello() {
return "Hello, World";
}
}
82
41
Example 3: Stateless Session
Bean, v3
• Container generates the business interface
(all methods will be exposed)
package examples.session.stateless;
import javax.ejb.Remote;
import javax.ejb.Stateless;
Communication
Software
2009-2010
// Stateless session bean
@Stateless
@Remote
public class HelloBean {
public String hello() {
return "Hello, World";
}
}
83
© The Authors
Example 4: EJB 3 Stateful
Session Bean
• One method should be annotated with @Remove
@Remote public interface ShoppingCart {
public void addItem(int prodId, int quantity);
public void checkout();
}
@Stateful public class ShoppingCartBean
implements ShoppingCart {
@Remove
public void checkout()
… }
{
}
Communication
Software
2009-2010
© The Authors
84
42
Dependency Injection in EJBs
via Environment Annotations
• Referencing other EJBs via @EJB
– as class annotation: not injection
• just binding name to reference in ENC (see later)
– as field annotation: field injection
• container injects reference to EJB into field
– as setter annotation: setter injection
• container invokes setter method with injected reference as parameter
– elements name, beanName, beanInterface,…
• Referencing other resources via @Resource
– for resources other than EJBs, persistence units / contexts
– as class annotation: not injection
• just binding name to reference in ENC (see later)
Communication
Software
2009-2010
– as field /setter annotation: field / setter injection
– elements name, type, authenticationType,…
85
© The Authors
The JNDI Enterprise Naming
Context (1/2)
• Each bean has its enterprise naming context (ENC)
– its own part of the JNDI name space
– to store references to resources, other EJBs,…
– identified by bean instance via java:comp/env
• Populating the ENC (bind)
– can be specified via instructions in deployment descriptor
– ‘side-effect’ of dependency injection via environment annotations
– entries placed in component’s ENC by container on deployment
• Accessing the ENC (lookup)
– via JNDI javax.naming.InitialContext.lookup()
– via EJBContext.lookup() (slightly simpler)
• EJBContext object can be obtained via injection (@Resource)
Communication
Software
2009-2010
© The Authors
• session beans: use SessionContext (extends EJBContext)
86
43
The JNDI Enterprise Naming
Context (2/2)
• Dependency injection via environment annotations
– is alternative to obtaining dependencies by lookup in ENC
– but has ‘side-effect’ of binding name in ENC
• Binding of name in ENC as ‘side-effect’ of dependency injection
– enables injection to be overriden in deployment descriptor
– what name is bound to reference in ENC
• use name of annotated construct: default
• specify name using name element of annotation
Communication
Software
2009-2010
87
© The Authors
Example 5: Dependency Injection
• Bean class specifies dependencies not lookup
– possible to test EJBs outside of the container
– several different annotations possible
@Stateful public class ShoppingCartBean
implements ShoppingCart {
@Resource private SessionContext ctx;
@EJB(name="CreditProcessorEJB")
private CreditCardProcessor processor;
"
private DataSource jdbc;
Communication
Software
2009-2010
© The Authors
@Resource(name="java:/DefaultDS")
public void setDataSource(DataSource db) {
this.jdbc = db;
}
}
88
44
Resource Management in
Stateless Session Beans:
Instance Pooling (1/2)
•
No reason to keep separate instance for each client
– EJB clients do not access EJB instances directly
• access via proxy object
– stateless session beans have no client-dpdnt state, though
• can have method variables
• can obtain information from JNDI ENC or database
•
Instance pooling and instance swapping
– server maintains a pool of pre-created instances
– instance associated to proxy dynamically (per invocation)
• successive invocations by client may be served by different instances
• same bean instance may be swapped between clients / proxies
– few stateless session
simultaneous clients
– resource management:
Communication
Software
2009-2010
bean
instances
can
serve
many
• high dynamicity: save instance creation time on invocation
• efficient use of memory: minimise number of instances
89
© The Authors
Resource Management in
Stateless Session Beans:
Instance Pooling (2/2)
•
Instance pooling also used in message-driven beans
– beans subscribe to a specific message channel
– producers deliver messages to one of the channels
– container creates a pool of beans for each channel
•
Instance pooling also used in EJB2.1 entity beans
– entity bean in pool not associated to persistent data
– not detached from persistence layer as in JPA entities
• pooled entity beans have uninitialised attributes
Communication
Software
2009-2010
© The Authors
90
45
Resource Management in
“Stateful”
Session Beans: Activation &
Passivation
•
No instance pooling for “stateful” session beans
– state of conversation with client must be maintained throughout
the life of the service provided to that client
•
Container may use activation/“passivation”
– resource management: gain space, lose time
• adequate for high memory usage, low dynamicity application
– mechanism is transparent to the client
•
“Passivation”:
– dissociation of EJB object (bean class proxy) from bean instance
– serialization of instance state to secondary storage
•
Activation:
– deserialization of instance state from secondary storage
– restoring of association to EJB object
Communication
Software
2009-2010
91
© The Authors
Activation/“Passivation” in EJB2
•
Term also applied to EJB2 entity beans
– refers to moving to and from instance pool
•
“Passivation”
– cut connection with EJB object (proxy for bean class)
– store bean data in underlying data base
• attribute values of pooled bean no longer significant
– free any resources being used by the bean
– place bean in pool
•
Communication
Software
2009-2010
© The Authors
Activation
– pick an anonymous bean from the pool
– acquire resources to be used by the bean
– load data from underlying data base into bean attributes
– restore connection with EJB object
92
46
Session Bean Life-Cycle Call-Back
Methods
• Methods called by EJB container
– session bean optionally registers for call-back on life-cycle events
• by annotating methods of bean class
– restrictions on methods
• must be declared public, have no arguments and return void
• cannot throw application exceptions
– may be placed in a separate listener class
• declared via annotation @Interceptors
• Call-back life-cycle methods for any type of session bean
– method annotated @PostConstruct
• called by container just after creating a new instance of class
– method annotated @Predestroy
• called by container before destruction, after @Remove method finishes
• Method annotated with @Remove
Communication
Software
2009-2010
– not a call-back method
– tells container that bean can be removed when method returns
93
© The Authors
Stateful Session Bean Call-Back
Methods
• Life-cycle call-back methods specific to stateful session beans
– method annotated @PrePassivate
• called by container just before “passivating” the bean
• e.g. to relinquish resources such as sockets, database connnections
– method annotated @PostActivate
• called by container just after activating the bean
• e.g. to restore resources such as sockets, database connnections
Communication
Software
2009-2010
© The Authors
94
47
Session Bean Life-Cycle
•
Creation of session bean
–
container decides to instantiate bean
–
–
container injects any required context dependencies
container calls any optional @PostConstruct callback methods
•
•
Use of session bean
–
container can call business methods on behalf of clients
•
•
recall: client calls proxy, container calls bean instance
Destruction of session bean
–
–
container decides to remove bean
container calls any optional @PreDestroy callback methods
•
–
Communication
Software
2009-2010
calls Class.newInstance()
not called on crash → pro-active houskeeping necessary
bean instance ready for garbage collection
© The Authors
Stateless Session Bean LifeCycle
Source: The Java EE 5 tutorial. Sun Microsystems
•
Creation and destruction
–
creation:
•
•
–
Communication
Software
2009-2010
if no pooling: when a client seeks to obtain a bean reference
if pooling: when container policy requires it
destruction
•
•
if no pooling: when invocation returns
if pooling: when container policy requires it
© The Authors
48
Stateful Session Bean Life-Cycle
Source: The Java EE 5 tutorial. Sun Microsystems
• Creation and destruction
– creation:
• when a client seeks to obtain a bean reference
– destruction:
• when client calls method annotated @remove or on timeout
• Activation and “passivation”
– “passivation”, after calling any optional @PrePassivate methods
Communication
Software
2009-2010
© The Authors
• when limit of instantiated beans is reached
– activation, after calling any optional @PostActivate methods
• when a client invokes a business method
Transactions
• Transaction:
– set of tasks to be executed atomically
• if one or more task fails: rollback
• if all tasks are successful: commit
– ACID properties
• Atomicity, Consistency, Isolation, Durability
• Two ways of managing transactions in EJB
– declarative transactions (default policy)
• container-managed transaction demarcation (CMT)
– programmatic transactions
Communication
Software
2009-2010
© The Authors
• bean-managed transaction demarcation (BMT)
• client-initiated transactions
– pros: client aware if transaction has rolled-back or committed
– cons: performance problems
98
49
Container-Managed Transactions
• Easy to use
• Transactional behaviour
– independent of business logic
• Uses transactional attributes to control propagation
– declared as annotations or in deployment descriptor
– associated with each EJB method
• Container uses JTS API to automatically manage
– transaction start and finish
– interaction with DB
– creation & propagation of context during transaction
Communication
Software
2009-2010
99
© The Authors
Bean-Managed Transactions
• Difficult to use
– but finer control
• Transactional behaviour
– may depend on business logic
• Explicit use of
– Java Transaction API (JTA)
– JDBC, if needed
• e.g. session bean wrapping legacy code
• Developer explicitly codes (in client or EJB)
– transaction start
– transaction completion or abort
Communication
Software
2009-2010
© The Authors
100
50
Java Transaction APIs
• Java Transaction Service (JTS)
– set of low-level APIs
– not used by application developers
• used by developers of transaction managers, application
servers, EJB containers, etc.
– transactional integrity not guaranteed
• guaranteed to applications by container
• Java Transaction API (JTA)
– higher-level API
– used by application developers
– specifies interfaces between transaction manager and all
objects involved
Communication
Software
2009-2010
• main interface: UserTransaction
© The Authors
Definitions
• Transactional context
– defines transactional scope and participant objects & operations
– by default, propagates between transactional objects such as EJBs
• Transactional objects
– objects whose methods are invoked in transaction
– may only be associated with one transaction at a time
• Transactional attributes
– per-method spec of transaction management (by container) on
invocation
• Transactional client
– agent that invokes methods on transactional objects
Communication
Software
2009-2010
• Transaction manager
– agent that coordinates the transaction processing
© The Authors
51
CMT: Transactional Attributes
(1/4)
•
Specified via annotation @TransactionAttribute
– as method annotation
– as class annotation: applies to all methods of the class
or via deployment descriptor
•
Enumeration TransactionAttributeType, 6 possible values
1.
2.
3.
4.
5.
6.
Communication
Software
2009-2010
Required
RequiresNew
NotSupported
Supports
Mandatory
Never
– Default value (no TransactionAttribute annotation & no
deployment descriptor)
– Required
© The Authors
CMT: Transactional Attributes
(2/4)
• Required (default value):
– if invoker has transaction context, it is propagated to bean
– otherwise, container creates new transaction context
– method always executes within a transaction context
• but does not create a new transaction needlessly
– use: methods that update databases or other resource
managers that support transactions
• RequiresNew:
Communication
Software
2009-2010
– if invoker has transaction context, it is suspended for the
duration of this method's execution
– in all cases, new transaction context is created
– use when do not want failure in transaction to cause failure
in a wider transaction
© The Authors
52
CMT: Transactional Attributes
(3/4)
• Supports:
– if invoker has transaction context, it is propagated to bean
– otherwise, no transaction context used
– use for "don't care" situations (use “don’t care” carefully!
varying transactional behaviour can be tricky)
• e.g. method carrying out a single update operation
• NotSupported:
Communication
Software
2009-2010
– if invoker has transaction context, it is suspended for the
duration of this method's execution
– otherwise, no transaction context used
– in all cases, method executes without transaction context
– example use: resource managers that do not propagate the
transaction
© The Authors
CMT: Transactional Attributes
(4/4)
• Mandatory:
– if invoker has a transaction context, it is propagated to bean
– otherwise, exception is thrown
• TransactionRequiredException
• TransactionRequiredLocalException
– use when invoker is to provide the transaction
• does not necessarily imply BMT or client-managed
transactions: invoker can be different method in same EJB
• Never:
– if invoker has transaction context, an exception is thrown
• RemoteException or EJBException
– otherwise, method proceeds normally, without a context
– used for non-transactional resources
Communication
Software
2009-2010
© The Authors
53
CMT: Transactional Attributes,
Summary
Transactional
attribute
Required
RequiresNew
Supports
NotSupported
Mandatory
Communication
Software
2009-2010
Never
Invoker’s transaction
context
Business method’s transaction
context
T
T
None
new context created by container
T
new context created by container
None
new context created by container
T
T
None
None
T
None
None
None
T
T
None
Exception
T
Exception
None
None
© The Authors
Example: Setting Transaction
Attributes
in a Deployment Descriptor
Communication
Software
2009-2010
// Source: Enterprise Java Beans 3.0, 5th edition, Burke et al.
<ejb-jar ...>
...
<assembly-descriptor>
...
<container-transaction>
<method>
<ejb-name>TravelAgentEJB</ejb-name>
<method-name> * </method-name>
</method>
<trans-attribute>NotSupported</trans-attribute>
</container-transaction>
<container-transaction>
<method>
<ejb-name>TravelAgentEJB</ejb-name>
<method-name>listAvailableCabins</method-name>
</method>
<trans-attribute>Required</trans-attribute>
</container-transaction>
...
</assembly-descriptor>
...
</ejb-jar>
© The Authors
54
Transaction Attributes in Entities
& MDB
•
EJB3 spec recommendation concerning JPA entities
– entity managers should be invoked from active JPA transaction
• should not use JPA local transactions (EntityTransaction interface)
• some exceptions
– entities do no use transaction attributes
•
EJBs that handle persistent entities
– CMT: only use Required, RequiresNew, or Mandatory
• ensures all database access inside JTA transaction
– new persistence context created if one doesn’t already exist
• usual case: entity manager has transaction-scoped persistence context,
i.e. persistence context ends when JTA transaction completes
• exception: stateful session beans & extended persistence context
•
Communication
Software
2009-2010
Message-driven beans
– CMT: only use NotSupported or Required
• since other types apply to client-initiated transactions (no client!)
© The Authors
CMT
• Methods of EJBContext class for use with CMT only:
– setRollBackOnly
• called by a business method to instruct the container to roll
back the transaction
• usually called before throwing an exception
– getRollBackOnly
• tests whether container has marked current CMT for rollback
• avoids executing work that would not be committed
• Stateful session beans using CMT
– may use the SessionSynchronization interface
Communication
Software
2009-2010
© The Authors
55
BMT
•
A business method can initiate a new transaction
– declare use of BMT via @TransactionManagement annotation
– obtain a UserTransaction object
• via EJBContext.getUserTransaction() or by injection
– call its begin method to associate a transaction to current thread
•
UserTransaction object
– propagated to other EJBs on method invocation
• unless also declaring use of BMT
– methods:
• begin, commit, rollback, setRollbackOnly,…
• no getRollBackOnly method
•
Bean instance that created the transaction
– is responsible for ending it (commit or roll back)
Communication
Software
2009-2010
• stateless session beans: initiating method must end it.
– cannot start a new transaction until previous one is completed
© The Authors
Example 6: Programmatic
Transactions
[...]
InitialContext cxt = new InitialContext();
userTx = (javax.transaction.UserTransaction)
cxt.lookup("java:comp/UserTransaction");
Communication
Software
2009-2010
try{
userTx.begin();
beanA.setX(1);
beanA.setName("one");
beanB.setY(2);
beanB.setName("two");
userTx.commit();
} catch(Exception e){
try{
System.out.println(e.getMessage());
userTx.rollback();
} catch(Exception ex){}
}
[...]
© The Authors
56
Stateful Session Beans and
SessionSynchronization
Interface
•
Stateful session beans using CMTs can receive transaction
event notifications
– bean can synchronise its state with database
• enables bean to cache changes before applying them to database
– bean simply implements SessionSynchronization interface
•
Communication
Software
2009-2010
SessionSynchronization interface has three methods:
– afterBegin
• notifies bean instance that a new transaction has started
– beforeCompletion
• notifies bean instance that a transaction is about to be
committed (bean can then write cached data to database)
– afterCompletion(boolean committed)
• notifies bean instance that a transaction commit protocol has
completed, and whether it was committed or rolled back (if
rolled back, bean won’t write cached data to database)
© The Authors
Stateful Session Beans
and Extended Persistence
Context
• Transactional persistence context (default)
– entity detached from persistence context after method call
• Stateful session bean has conversational state
– clients retrieve multiple entities and interact with them through a
number of invocations
– require loaded entities to stay managed (not detached) between
method calls
– solution: extended persistence context (ends when bean removed)
• Extended persistence context
– annote declaration of entity manager as follows
@PersistenceContext(type=EXTENDED)
– can invoke persist(), merge(), remove outside of a transaction
Communication
Software
2009-2010
• inserts, updates, deletes queued until persistence context enlisted in a
transaction
• may justify use of NotSupported in some methods of EJB with entities
© The Authors
57
Transactional Isolation
• See JDBC slides for info. about transaction isolation levels
• Higher isolation level:
– fewer concurrency problems
– lower performance
• JPA default isolation level: Read Committed
• CMT
– isolation level set by deployer in vendor-specific way
• BMT: isolation level can be specified from EJB using DB API
– JDBC: use Connection.setTransactionIsolation()
• CMT & BMT
– can use programmatic locking: EntityManager.lock()
Communication
Software
2009-2010
© The Authors
Bibliography for Section 3
•
Mastering Enterprise JavaBeans 3.0. Rima Patel Sriganesh, Gerald Brose,
Micah Silverman. Wiley 2006.
http://www.theserverside.com/tt/books/wiley/masteringEJB3/index.tss
•
Enterprise JavaBeans 3.0, 5th edition. Bill Burke, Richard Monson-Haefel.
OReilly 2006.
http://proquest.safaribooksonline.com/059600978X
Beginning EJB 3 application development: from novice to professional. Raghu
Kodali, Jonathan Wetherbee, Peter Zadrozny. Apress 2006.
http://books.google.com/books?id=xnbJkOIZfFgC
•
EJB 3 in Action. Debu Panda, Reza Rahman, Derek Lane. Manning 2007
•
Enterprise JavaBeans Technology. Sun Microsystems.
http://java.sun.com/products/ejb/
•
JSR 220: Enterprise JavaBeans 3.0. The Java Community Process 2006.
•
JBoss tutorials. JBoss 2009
http://jcp.org/en/jsr/detail?id=220
Communication
Software
2009-2010
http://www.jboss.org/ejb3/docs/
© The Authors
58
3. Appendix: Enterprise JavaBeans v2
(non-examinable material)
Communication
Software
2009-2010
117
© The Authors
Structure of EJB 2.1 (1/2)
1. Enterprise bean client-view API: defines
– remote interfaces, for access from outside the container
• remote home interface: class-level methods
• remote business interface: instance-level methods
– local interfaces, for access from inside the container
• local home interface: class-level methods
• local business interface: instance-level methods
2. Enterprise bean class: implements
– business methods (instance-level)
• called by a client (e.g. another EJB) via client-view API
• EJB 2: class-level business methods for entity beans
– life-cycle methods (class-level)
• called by the container
Communication
Software
2009-2010
© The Authors
– other methods (instance level or class-level)
• called by the bean class itself
118
59
Structure of EJB 2.1 (2/2)
3. Deployment descriptor: XML document declaring:
– information about the EJB, in particular:
•
•
•
•
name of the EJB
name of the EJB class
type of the EJB
name of the home and remote interfaces
– information about the EJB’s environment
•
•
•
services the EJB expects from its container
dependencies on other EJBs and resource managers
c.f. the CBD notion of “required interfaces”
Communication
Software
2009-2010
119
© The Authors
Characteristics of EJB 2.1 ClientView
• Remote interfaces
– home interface (container generates one object per class)
• create and delete session and entity beans, find entity beans
• extends javax.ejb.EJBHome
– remote business interface (container generates proxy)
• export business methods (remotely)
• extends javax.ejb.EJBObject
• Local interfaces
– local home Interface (container generates 1 object per class)
• create and delete session and entity beans, find entity beans
• extends javax.ejb.EJBLocalHome
– local business interface (container generates proxy)
Communication
Software
2009-2010
© The Authors
• export business methods (locally)
• extends javax.ejb.EJBLocalObject
120
60
Example 7: HelloWorldEJB
(EJB 2)
Bean Class
Remote interfaces
Local interfaces
extends
implements
Deployment Descriptor
name=HelloWorldEJB
class=HelloBean
home=HelloHome
Type=Session
Transaction=Container
…
Communication
Software
2009-2010
© The Authors
121
Example 7: EJB 2 Remote
Interfaces
import java.rmi.RemoteException;
import javax.ejb.CreateException;
public interface HelloHome extends javax.ejb.EJBHome {
// create methods
Hello create() throws RemoteException, CreateException;
}
import java.rmi.RemoteException;
public interface Hello extends javax.ejb.EJBObject {
public String hello() throws RemoteException;
Communication
Software
2009-2010
© The Authors
}
122
61
Example 7: EJB 2 Local
Interfaces
import javax.ejb.CreateException;
public interface HelloLocalHome
extends javax.ejb.EJBLocalHome {
// create methods
HelloLocal create() throws CreateException;
}
public interface HelloLocal
extends javax.ejb.EJBLocalObject {
public String hello();
}
Communication
Software
2009-2010
123
© The Authors
Example 7: EJB 2 HelloBean
Class
import javax.ejb.RemoveException;
import javax.ejb.SessionContext;
// javax.ejb.SessionBean known as the "component interface"
public class HelloBean implements javax.ejb.SessionBean {
// life cycle methods declared on home interface
public void ejbCreate() {...}
// container callbacks from implementing cmpnt interface
public void ejbRemove() throws RemoveException {...}
public void setSessionContext(SessionContext sc) {...}
public void ejbActivate() {...}
public void ejbPassivate() {...}
Communication
Software
2009-2010
© The Authors
// business methods declared on business interface(s)
public String hello() {
return "Hello, World!";
}
}
124
62
Example 7: EJB 2 Deployment
Descriptor
Communication
Software
2009-2010
<ejb-jar
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/ejb-jar_2_1.xsd"
version="2.1">
<enterprise-beans>
<session>
<ejb-name>HelloWorldEJB</ejb-name>
<home>examples.ejb21.HelloHome</home>
<remote>examples.ejb21.Hello</remote>
<local-home>examples.ejb21.HelloLocalHome</local-home>
<local>examples.ejb21.HelloLocal</local>
<ejb-class>examples.ejb21.HelloBean</ejb-class>
<session-type>Stateless</session-type>
<transaction-type>Container</transaction-type>
</session>
</enterprise-bean>
</ejb-jar>
125
© The Authors
EJB2 & EJB3, summary of
differences (1/2)
EJB2
EJB3
Business interface
Business interface
• must extend special interface
• just a normal Java interface (POJI)
• connection with bean class made in • connection with bean class made with
Java implements keyword (POJI)
deployment descriptor
• one single interface with @Remote and/or
• local and/or remote interfaces
@Local annotation
Home interface
• for create(), find(), etc.
• must extend special interface
• local and/or remote interfaces
Communication
Software
2009-2010
Home interface
• no home interface needed
Bean class
Bean class
• access to bean environment via
JNDI lookup (usually in ENC)
• no inheritance or polymorphism
• must implement cmpnt interface
(many callback methods often empty)
• simplified access to bean environment via
dependency injection
• just a normal Java class (POJO)
• POJO
© The Authors
63
EJB2 & EJB3, summary of
differences (2/2)
EJB2
EJB3
XML deployment descriptor
• mandatory for metadata description
XML deployment descriptor
• cons: complex and verbose
• pros: all appl. metadata in one file
• Java5 annotations can be used instead
• pros: annotations much simpler
• pros: can also use deployment descriptor
Bean client
Bean client
• needs CORBA casting (narrow)
• access to bean via JNDI lookup
• no CORBA casting needed
• simplified access to bean via dependency
injection for client on same appl. server
Persistence via entity beans
Persistence via JPA
• entities (POJOS) + EntityManager
• BMP or CMP entity bean
• much of CMP-bean ORM implicit & • ORM explicit and controllable
not controllable by developer
developer (but with defaults)
Testing
Communication
Software
2009-2010
by
Testing
• EJBs (including entity beans) not • EJBs & JPA entities both testable outside
testable outside the container
the container (beans are POJOs)
© The Authors
EJB 2 Programming Model
Communication
Software
2009-2010
© The Authors
Source: Mastering Enterprise JavaBeans 3.0, Patel et al.
128
64
EJB 3 Programming Model
Communication
Software
2009-2010
© The Authors
Source: Mastering Enterprise JavaBeans 3.0, Patel et al.
129
Bibliography for Appendix
•
Enterprise JavaBeans, 4th edition. Bill Burke, Richard Monson-Haefel.
OReilly 2004.
http://proquest.safaribooksonline.com/059600530X
•
Mastering Enterprise JavaBeans, 3rd edition. Ed Roman, Rima Patel
Sriganesh, Gerald Brose. Wiley 2005.
http://www.theserverside.com/tt/books/wiley/masteringEJB/index.tss
Communication
Software
2009-2010
© The Authors
65
Was this manual useful for you? yes no
Thank you for your participation!

* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project

Download PDF

advertisement