Upload
others
View
2
Download
0
Embed Size (px)
Citation preview
1
Communication Software
2010-2011
© The Authors
The Business Tierof the Java EE Architecture
Authors: Simon PickinFlorina Almenárez MendozaNatividad Martínez Madrid
Address: Departamento de Ingeniería TelemáticaUniversidad Carlos III de MadridSpain
Version: 1.1
Acknowledgements: Bill Burke, JBoss Group, Tal Cohen, IBM Haifa
Communication Software
2010-2011
© The Authors
Contents
1. Introduction– EJBs and the EJB container
– modelling enterprise applications– types of EJB– resource management with EJBs
2. EJB3 Session Beans– stateful and stateless session bean examples– call-back methods and the session bean life-cycle
– ENC and dependency injection
3. Transactions in EJBs– CMT, BMT and the Java transaction APIs– CMT transactional attributes
– session synchronisation, extended persistence context, transactional isolation
4. Comparison EJB2 and EJB3
2
3
Communication Software
2010-2011
© 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.
– components: reuse y abstraction
– compatible with other Java APIs
Communication Software
2010-2011
© The Authors 4
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)• 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
3
Communication Software
2010-2011
© The Authors 5
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 JAX-
WS API or older JAX-RPC API)• may also support other communication protocols
– container implements distributed calls using communication infrastructure
• e.g. generates stubs and skeletons
Communication Software
2010-2011
© The Authors 6
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• maintain instance pool & direct requests to bean instances from pool• serialize requests to a single bean instance
4
Communication Software
2010-2011
© The Authors 7
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• any enterprise bean can be an emitter of messages
Communication Software
2010-2011
© The Authors 8
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 JPA entities
• EJB3 container must support EJB2.1 entity beans (legacy 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)• 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
5
9
Communication Software
2010-2011
© The Authors
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
10
Communication Software
2010-2011
© The Authors
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
6
11
Communication Software
2010-2011
© 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)
12
Communication Software
2010-2011
© The Authors
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)
7
13
Communication Software
2010-2011
© 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: – processes executed as a response to the reception of a message
– receive asynchronous calls via a channel
14
Communication Software
2010-2011
© The Authors
JPA Entities (EJB3) / Entity Beans (EJB2)
• 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)
• JPA entities only: can be detached from and re-attached to (merged with) persistence layer
8
15
Communication Software
2010-2011
© 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
16
Communication Software
2010-2011
© The Authors
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• may use client 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
– state not persistent: lost when client releases bean
– each instance has different identity
9
Communication Software
2010-2011
© The Authors 17
Resource Management in Stateless SessionBeans: Instance Pooling / Swapping
• No reason to keep separate instance for each client– EJB clients do not access EJB instances directly
• access via proxy object IMPORTANT!
– 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 bean instances can serve many simultaneous clients
– resource management:• high dynamicity: save instance creation time on invocation• efficient use of memory: minimise number of instances
Communication Software
2010-2011
© The Authors 18
Resource Management in Message-Driven / EJB 2.1 Entity Beans: Instance Pooling
• 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
10
Communication Software
2010-2011
© The Authors 19
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 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 bean class proxy
Communication Software
2010-2011
© The Authors
Contents
1. Introduction– EJBs and the EJB container
– modelling enterprise applications– types of EJB– resource management with EJBs
2. EJB3 Session Beans– stateful and stateless session bean examples– call-back methods and the session bean life-cycle
– ENC and dependency injection
3. Transactions in EJBs– CMT, BMT and the Java transaction APIs– CMT transactional attributes
– session synchronisation, extended persistence context, transactional isolation
4. Comparison EJB2 and EJB3
11
21
Communication Software
2010-2011
© 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– 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
Communication Software
2010-2011
© The Authors 22
Example 1: EJB3 Stateless Session Bean v1
package examples.session.stateless;
// This is the Hello business interfacepublic interface Hello {
public String hello();}
package examples.session.stateless;
import javax.ejb.Remote;import javax.ejb.Stateless;
// Stateless session bean@Stateless@Remote(Hello.class)public class HelloBean implements Hello {
public String hello() {
return "Hello, World";}
}
12
Communication Software
2010-2011
© The Authors 23
Example 1: EJB3 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;
// Stateless session bean@Statelesspublic class HelloBean implements Hello {
public String hello() {return "Hello, World";
} }
Communication Software
2010-2011
© The Authors 24
Example 1: EJB3 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;
// Stateless session bean@Stateless@Remotepublic class HelloBean {
public String hello() {return "Hello, World";
} }
Source of example 1: Mastering Enterprise JavaBeans 3.0
13
Communication Software
2010-2011
© The Authors 25
Example 1: EJB3 Session Bean Client
import javax.naming.context;import javax.naming.InitialContext;
// EJB3 stateless session bean clientpublic class HelloClient {
public static void main(String[] args) throws Excep tion {
// Dependency injection (see later)// If client on same application server as bean,// could replace above 2 imports and next 2 lines with :// @EJB Hello hello;Context ctx = new InitialContext();Hello hello = (Hello) ctx.lookup("Hello") ;
System.out.println(hello.hello());}
}
Source of example 1: Mastering Enterprise JavaBeans 3.0
Communication Software
2010-2011
© The Authors 26
Example 2: EJB 3 Stateful Session Bean
@Remote public interface ShoppingCart {public void addItem(int prodId, int quantity);public void checkout();
}
@Stateful public class ShoppingCartBeanimplements ShoppingCart {
@Removepublic void checkout() {
… } }
• One method should be annotated with @Remove
14
27
Communication Software
2010-2011
© The Authors
Session Bean Life-Cycle Call-Back Methods
• Call-back methods are 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 @Removemethod finishes
• Method annotated with @Remove
– not a call-back method– tells container that bean can be removed when method returns
28
Communication Software
2010-2011
© 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
15
Communication Software
2010-2011
© The Authors
Session Bean Life-Cycle
• Creation of session bean– container decides to instantiate bean
• calls Class.newInstance()
– 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
• not called on crash → pro-active houskeeping necessary
– bean instance ready for garbage collection
Communication Software
2010-2011
© The Authors
Stateless Session Bean Life-Cycle
• Creation and destruction– creation:
• 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
Source: The Java EE 5 tutorial. Sun Microsystems
16
Communication Software
2010-2011
© The Authors
Stateful Session Bean Life-Cycle
• 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
• when limit of instantiated beans is reached
– activation, after calling any optional @PostActivate methods• when a client invokes a business method
Source: The Java EE 5 tutorial. Sun Microsystems
32
Communication Software
2010-2011
© The Authors
Dependency Injection in EJBsvia 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)
– as field /setter annotation: field / setter injection– elements name, type , authenticationType ,…
17
33
Communication Software
2010-2011
© 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
• Accessing the ENC via lookup
– via JNDI javax.naming.InitialContext.lookup()
– via EJBContext .lookup() (slightly simpler)• EJBContext object can be obtained via injection (@Resource)• session beans: use SessionContext (extends EJBContext )
• Populating the ENC via 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
34
Communication Software
2010-2011
© The Authors
The JNDI Enterprise Naming Context (2/2)
• Dependency injection via environment annotations– is alternative to obtaining dependencies by lookup in ENC
• for resources located on same application server
– 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
18
Communication Software
2010-2011
© The Authors 35
Example 3: Dependency Injection
• Bean class specifies dependencies not lookup– possible to test EJBs outside of the container– several different annotations possible
@Stateful public class ShoppingCartBeanimplements ShoppingCart {
@Resource private SessionContext ctx;
@EJB(name="CreditProcessorEJB")private CreditCardProcessor processor;
"private DataSource jdbc;
@Resource(name="java:/DefaultDS")public void setDataSource(DataSource db) {
this.jdbc = db;}
}
Communication Software
2010-2011
© The Authors
Contents
1. Introduction– EJBs and the EJB container
– modelling enterprise applications– types of EJB– resource management with EJBs
2. EJB3 Session Beans– stateful and stateless session bean examples– call-back methods and the session bean life-cycle
– ENC and dependency injection
3. Transactions in EJBs– CMT, BMT and the Java transaction APIs– CMT transactional attributes
– session synchronisation, extended persistence context, transactional isolation
4. Comparison EJB2 and EJB3
19
Communication Software
2010-2011
© The Authors 37
Transaction Management in EJBs
• 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• bean-managed transaction demarcation (BMT)• client-initiated transactions
– pros: client aware if transaction has rolled-back or committed– cons: performance problems
Communication Software
2010-2011
© The Authors 38
Container-Managed Transactions (CMT)
• 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
20
Communication Software
2010-2011
© The Authors 39
Bean-Managed Transactions (BMT)
• 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
2010-2011
© The Authors
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
• main interface: UserTransaction
21
Communication Software
2010-2011
© The Authors
CMT: interface and methods
• 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
2010-2011
© The Authors
BMT: interface and methods
• 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)
• stateless session beans: initiating method must end it.
– cannot start a new transaction until previous one is completed
22
Communication Software
2010-2011
© The Authors
Example 4: BMT
[...]InitialContext cxt = new InitialContext(); userTx = (javax.transaction.UserTransaction)
cxt.lookup("java:comp/UserTransaction");
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){} } [...]
Communication Software
2010-2011
© 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
• Transaction manager– agent that coordinates the transaction processing
23
Communication Software
2010-2011
© The Authors
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 values1. Required
2. RequiresNew
3. NotSupported
4. Supports
5. Mandatory
6. Never
– Default value (no TransactionAttribute annotation & no deployment descriptor)– Required
Communication Software
2010-2011
© 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 :– 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
24
Communication Software
2010-2011
© The Authors
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 :– 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
Communication Software
2010-2011
© 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
25
Communication Software
2010-2011
© The Authors
CMT: Transactional Attributes, Summary
Exception
None
T
None
Never
T
Exception
T
None
Mandatory
None
None
T
None
NotSupported
T
None
T
None
Supports
new context created by container
new context created by container
T
None
RequiresNew
T
new context created by container
T
None
Required
Business method’s transaction context
Invoker’s transaction context
Transactional
attribute
Communication Software
2010-2011
© The Authors
Example: Setting Transaction Attributesin a Deployment Descriptor
// Source: Enterprise Java Beans 3.0, 5th edition, Burk e 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>
26
Communication Software
2010-2011
© The Authors
Transaction Attributes, Entities and 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
• Message-driven beans– CMT: only use NotSupported or Required
• since other types apply to client-initiated transactions (no client!)
Communication Software
2010-2011
© The Authors
Stateful Session Beans andSessionSynchronization 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
• 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)
27
Communication Software
2010-2011
© The Authors
Stateful Session Beansand 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) betweenmethod 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• inserts, updates, deletes queued until persistence context enlisted in a
transaction• may justify use of NotSupported in some methods of EJB with entities
Communication Software
2010-2011
© The Authors
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()
28
Communication Software
2010-2011
© The Authors
Contents
1. Introduction– EJBs and the EJB container
– modelling enterprise applications– types of EJB– resource management with EJBs
2. EJB3 Session Beans– stateful and stateless session bean examples– call-back methods and the session bean life-cycle
– ENC and dependency injection
3. Transactions in EJBs– CMT, BMT and the Java transaction APIs– CMT transactional attributes
– session synchronisation, extended persistence context, transactional isolation
4. Comparison EJB2 and EJB3
56
Communication Software
2010-2011
© The Authors
Structure of EJB 2 (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
– other methods (instance level or class-level)• called by the bean class itself
29
57
Communication Software
2010-2011
© The Authors
Structure of EJB 2 (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”
58
Communication Software
2010-2011
© The Authors
Characteristics of EJB 2 Client-View
• 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 object)• 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 object)• export business methods (locally)• extends javax.ejb.EJBLocalObject
30
Communication Software
2010-2011
© The Authors 59
Example 5: EJB 2 Stateless Session Bean
implements
extends
Bean Class Remote interfaces Local interfaces
Deployment Descriptor
name=HelloWorldEJBclass=HelloBeanhome=HelloHomeType=SessionTransaction=Container…
Deployment Descriptor
name=HelloWorldEJBclass=HelloBeanhome=HelloHomeType=SessionTransaction=Container…
Compare with example 1
Communication Software
2010-2011
© The Authors 60
Example 5: EJB 2 Remote Interfaces
// source: Mastering Enterprise JavaBeans 3.0import java.rmi.RemoteException;
import javax.ejb.CreateException;
public interface HelloHome extends javax.ejb.EJBHome {// create methodsHello create () throws RemoteException, CreateException;
}
import java.rmi.RemoteException;
public interface Hello extends javax.ejb.EJBObject {
public String hello () throws RemoteException;
}
31
Communication Software
2010-2011
© The Authors 61
Example 5: 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
2010-2011
© The Authors 62
Example 5: 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 interfacepublic void ejbRemove () throws RemoveException {...}
public void setSessionContext (SessionContext sc) {...} public void ejbActivate () {...}
public void ejbPassivate () {...}
// business methods declared on business interface(s)
public String hello () {return "Hello, World!";
}}
32
Communication Software
2010-2011
© The Authors 63
Example 5: EJB 2 Deployment Descriptor
<ejb-jar
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instanc e"
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>
Communication Software
2010-2011
© The Authors 64
Example 5: EJB2 Session Bean Client
import javax.naming.context;import javax.naming.InitialContext;
// EJB2 stateless session bean clientpublic class HelloClient {
public static void main(String[] args) throws Excep tion {Context ctx = new InitialContext();Object obj = ctx. lookup("HelloHome") ;// CORBA casting and native Java castingHelloHome home = (HelloHome)
java.rmi.PortableRemoteObject.narrow(obj,HelloHome.class);
Hello hello = home.create ();System.out.println(hello.hello());hello.remove ();
}}
Source of example 5: Mastering Enterprise JavaBeans 3.0
33
Communication Software
2010-2011
© The Authors
EJB2 & EJB3, summary of differences (1/3)
Home interface• no home interface needed:
– session / message-driven beansbeans created by container as looked up;
– entity beansreplaced by JPA entities (POJOs)
Home interface• for create() , find() , etc. • must extend special interface• local and/or remote interfaces
Business interface• just a normal Java interface (POJI)• connection with bean class made with
Java implements keyword (POJI)• one single interface with @Remoteand/or
@Local annotation
Business interface• must extend special interface• connection with bean class made in
deployment descriptor• local and/or remote interfaces
Bean class• simplified access to bean environment via
dependency injection for local resources• just a normal Java class (POJO)• only those call back methods required
need be implemented
Bean class• access to bean environment via
JNDI lookup (usually in ENC)• no inheritance or polymorphism• must implement cmpnt interface
(callback methods often empty)
EJB3EJB2
Communication Software
2010-2011
© The Authors
EJB2 & EJB3, summary of differences (2/3)
Bean client• no CORBA casting needed• simplified access to bean via dpndncy
injection for client on same app. server
Bean client• needs CORBA casting (narrow )• access to bean via JNDI lookup
XML deployment descriptor• Java5 annotations can be used instead• pros: annotations much simpler• pros: can also use deployment descriptor
XML deployment descriptor• mandatory for metadata description• cons: complex and verbose• pros: all appl. metadata in one file
Testability• EJBs & JPA entities both testable outside
the container (beans are POJOs)
Testability• EJBs (including entity beans) not
testable outside the container
EJB3EJB2
34
Communication Software
2010-2011
© The Authors
EJB2 & EJB3, summary of differences (3/3)
JPA• no equivalent of BMP
BMP entity beans• database interaction code – in find
methods, business methods andcall-back methods (ejbLoad /ejbStore ) – written by developer
Persistence• JPA entities (POJOs) + EntityManager
Persistence• BMP or CMP entity bean
JPA• no database interaction code written by
the developer• the ORM is explicit and controllable by
the developer (but with defaults)• just a normal Java class (POJO)
CMP entity beans (EJB2.1)• no database interaction code written
by the developer• much of the ORM is implicit & not
controllable by the developer• bean class declared as abstract• getter & setter methods declared as
abstract• persistent attributes declared in
deployment descriptor; only getter &setter methods declared in code
EJB3EJB2
Communication Software
2010-2011
© The Authors 68
EJB 2 Programming Model
Source: Mastering Enterprise JavaBeans 3.0, Patel et al.
35
Communication Software
2010-2011
© The Authors 69
EJB 3 Programming Model
Source: Mastering Enterprise JavaBeans 3.0, Patel et al.
Communication Software
2010-2011
© The Authors 70
Activation/“Passivation” in Entity Beans
• Terms also applied to EJB2 entity beans
– refers to moving to and from instance pool
• “Passivation”
– cut connection with proxy object for bean instance
– 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
• 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 proxy object
36
Communication Software
2010-2011
© The Authors
Bibliography for Sections 1- 3
• Mastering Enterprise JavaBeans 3.0. Rima Patel Sriganesh, Gerald Brose, Micah Silverman. Wiley 2006.http://www.theserverside.com/tt/books/wiley/masteri ngEJB3/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. RaghuKodali, 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.http://jcp.org/en/jsr/detail?id=220
• JBoss tutorials. JBoss 2009http://www.jboss.org/ejb3/docs/
Communication Software
2010-2011
© The Authors
Bibliography for Section 4
• 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/masteri ngEJB/index.tss