Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
The Business Tier of the Java EE Architecture Communication Software 2010-2011 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.1 Acknowledgements: Bill Burke, JBoss Group, Tal Cohen, IBM Haifa © 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 – – – Communication Software 2010-2011 CMT, BMT and the Java transaction APIs CMT transactional attributes session synchronisation, extended persistence transactional isolation context, 4. Comparison EJB2 and EJB3 © The Authors 1 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 2010-2011 – components: reuse y abstraction – compatible with other Java APIs 3 © The Authors 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 2010-2011 © The Authors • 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 4 2 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 2010-2011 • e.g. generates stubs and skeletons 5 © The Authors 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 2010-2011 © The Authors • maintain instance pool & direct requests to bean instances from pool • serialize requests to a single bean instance 6 3 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 2010-2011 • any enterprise bean can be an emitter of messages 7 © The Authors 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) Communication Software 2010-2011 © 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 8 4 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 2010-2011 9 © 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 Communication Software 2010-2011 © The Authors 10 5 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 2010-2011 11 © 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) Communication Software 2010-2011 © The Authors 12 6 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 2010-2011 – processes executed as a response to the reception of a message – receive asynchronous calls via a channel 13 © 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) Communication Software 2010-2011 © The Authors • JPA entities only: can be detached from and re-attached to (merged with) persistence layer 14 7 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 2010-2011 15 © 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 Communication Software 2010-2011 © The Authors – state not persistent: lost when client releases bean – each instance has different identity 16 8 Resource Management in Stateless Session Beans: 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 simultaneous clients – resource management: Communication Software 2010-2011 bean instances can serve • high dynamicity: save instance creation time on invocation • efficient use of memory: minimise number of instances © The Authors many 17 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 Communication Software 2010-2011 © The Authors 18 9 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: Communication Software 2010-2011 – deserialization of instance state from secondary storage – restoring of association to bean class proxy 19 © 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 – – – Communication Software 2010-2011 CMT, BMT and the Java transaction APIs CMT transactional attributes session synchronisation, extended persistence transactional isolation context, 4. Comparison EJB2 and EJB3 © The Authors 10 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 2010-2011 – 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 21 © The Authors Example 1: EJB3 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 2010-2011 © The Authors // Stateless session bean @Stateless @Remote(Hello.class) public class HelloBean implements Hello { public String hello() { return "Hello, World"; } } 22 11 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; Communication Software 2010-2011 // Stateless session bean @Stateless public class HelloBean implements Hello { public String hello() { return "Hello, World"; } } 23 © The Authors 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 @Remote public class HelloBean { public String hello() { return "Hello, World"; } } Communication Software 2010-2011 © The Authors Source of example 1: Mastering Enterprise JavaBeans 3.0 24 12 Example 1: EJB3 Session Bean Client import javax.naming.context; import javax.naming.InitialContext; // EJB3 stateless session bean client public class HelloClient { public static void main(String[] args) throws Exception { // 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()); } } Communication Software 2010-2011 Source of example 1: Mastering Enterprise JavaBeans 3.0 25 © The Authors Example 2: 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 2010-2011 © The Authors 26 13 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 @Remove method finishes • Method annotated with @Remove Communication Software 2010-2011 – not a call-back method – tells container that bean can be removed when method returns 27 © 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 2010-2011 © The Authors 28 14 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 2010-2011 calls Class.newInstance() not called on crash → pro-active houskeeping necessary bean instance ready for garbage collection © The Authors Stateless Session Bean Life-Cycle Source: The Java EE 5 tutorial. Sun Microsystems • Creation and destruction – creation: • • – Communication Software 2010-2011 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 15 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 2010-2011 © The Authors • when limit of instantiated beans is reached – activation, after calling any optional @PostActivate methods • when a client invokes a business method 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 2010-2011 © The Authors – as field /setter annotation: field / setter injection – elements name, type, authenticationType,… 32 16 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 Communication Software 2010-2011 – 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 33 © 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 Communication Software 2010-2011 © The Authors 34 17 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 ShoppingCartBean implements ShoppingCart { @Resource private SessionContext ctx; @EJB(name="CreditProcessorEJB") private CreditCardProcessor processor; " private DataSource jdbc; Communication Software 2010-2011 @Resource(name="java:/DefaultDS") public void setDataSource(DataSource db) { this.jdbc = db; } } 35 © 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 – – – Communication Software 2010-2011 CMT, BMT and the Java transaction APIs CMT transactional attributes session synchronisation, extended persistence transactional isolation context, 4. Comparison EJB2 and EJB3 © The Authors 18 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 Communication Software 2010-2011 • bean-managed transaction demarcation (BMT) • client-initiated transactions – pros: client aware if transaction has rolled-back or committed – cons: performance problems © The Authors 37 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 Communication Software 2010-2011 © The Authors 38 19 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 39 © 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 Communication Software 2010-2011 • main interface: UserTransaction © The Authors 20 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) Communication Software 2010-2011 • stateless session beans: initiating method must end it. – cannot start a new transaction until previous one is completed © The Authors 21 Example 4: BMT [...] InitialContext cxt = new InitialContext(); userTx = (javax.transaction.UserTransaction) cxt.lookup("java:comp/UserTransaction"); Communication Software 2010-2011 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 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 2010-2011 • Transaction manager – agent that coordinates the transaction processing © The Authors 22 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 2010-2011 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 2010-2011 – 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 23 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 2010-2011 – 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 2010-2011 © The Authors 24 CMT: Transactional Attributes, Summary Transactional attribute Required RequiresNew Supports NotSupported Mandatory Communication Software 2010-2011 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 2010-2011 // 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 25 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 Communication Software 2010-2011 • since other types apply to client-initiated transactions (no client!) © The Authors 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 2010-2011 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 26 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 • 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() Communication Software 2010-2011 © The Authors 27 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 – – – Communication Software 2010-2011 CMT, BMT and the Java transaction APIs CMT transactional attributes session synchronisation, extended persistence transactional isolation context, 4. Comparison EJB2 and EJB3 © 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 Communication Software 2010-2011 © The Authors – other methods (instance level or class-level) • called by the bean class itself 56 28 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” Communication Software 2010-2011 57 © 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) Communication Software 2010-2011 © The Authors • export business methods (locally) • extends javax.ejb.EJBLocalObject 58 29 Example 5: EJB 2 Stateless Session Bean Bean Class Remote interfaces Local interfaces extends implements Deployment Descriptor Communication Software 2010-2011 Compare with example 1 © The Authors name=HelloWorldEJB class=HelloBean home=HelloHome Type=Session Transaction=Container … 59 Example 5: EJB 2 Remote Interfaces // source: Mastering Enterprise JavaBeans 3.0 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 2010-2011 © The Authors } 60 30 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 61 © The Authors 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 interface public void ejbRemove() throws RemoveException {...} public void setSessionContext(SessionContext sc) {...} public void ejbActivate() {...} public void ejbPassivate() {...} Communication Software 2010-2011 © The Authors // business methods declared on business interface(s) public String hello() { return "Hello, World!"; } } 62 31 Example 5: EJB 2 Deployment Descriptor Communication Software 2010-2011 <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> 63 © The Authors Example 5: EJB2 Session Bean Client import javax.naming.context; import javax.naming.InitialContext; Communication Software 2010-2011 // EJB2 stateless session bean client public class HelloClient { public static void main(String[] args) throws Exception { Context ctx = new InitialContext(); Object obj = ctx.lookup("HelloHome"); // CORBA casting and native Java casting HelloHome 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 © The Authors 64 32 EJB2 & EJB3, summary of differences (1/3) 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 2010-2011 Home interface • no home interface needed: – session / message-driven beans beans created by container as looked up; – entity beans replaced by JPA entities (POJOs) Bean class Bean class • access to bean environment via JNDI lookup (usually in ENC) • no inheritance or polymorphism • must implement cmpnt interface (callback methods often empty) • 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 © The Authors EJB2 & EJB3, summary of differences (2/3) EJB2 EJB3 XML deployment descriptor XML deployment descriptor • mandatory for metadata description • Java5 annotations can be used instead • cons: complex and verbose • pros: all appl. metadata in one file • 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 dpndncy injection for client on same app. server Testability Testability • EJBs (including entity beans) not testable outside the container • EJBs & JPA entities both testable outside the container (beans are POJOs) Communication Software 2010-2011 © The Authors 33 EJB2 & EJB3, summary of differences (3/3) Communication Software 2010-2011 EJB2 EJB3 Persistence Persistence • BMP or CMP entity bean • JPA entities (POJOs) + EntityManager BMP entity beans JPA • database interaction code – in find methods, business methods and call-back methods (ejbLoad / ejbStore) – written by developer • no equivalent of BMP CMP entity beans (EJB2.1) JPA • 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 • 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) © The Authors EJB 2 Programming Model Communication Software 2010-2011 © The Authors Source: Mastering Enterprise JavaBeans 3.0, Patel et al. 68 34 EJB 3 Programming Model Communication Software 2010-2011 © The Authors Source: Mastering Enterprise JavaBeans 3.0, Patel et al. 69 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 • Communication Software 2010-2011 © 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 proxy object 70 35 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/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. http://jcp.org/en/jsr/detail?id=220 • JBoss tutorials. JBoss 2009 http://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/masteringEJB/index.tss Communication Software 2010-2011 © The Authors 36