EJB3 Advance Features
Upcoming SlideShare
Loading in...5
×

Like this? Share it with your network

Share

EJB3 Advance Features

  • 1,367 views
Uploaded on

Enterprise Java Beans 3 Advance Features

Enterprise Java Beans 3 Advance Features

More in: Education , Technology
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
No Downloads

Views

Total Views
1,367
On Slideshare
1,367
From Embeds
0
Number of Embeds
0

Actions

Shares
Downloads
44
Comments
0
Likes
1

Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide

Transcript

  • 1. Cranking up advance features of EJB
  • 2. EJB3 beans are managed objects.The EJB container makes beans “special” by acting asa proxy between the client and the actual beaninstance.The container provides EJB services to the client onbehalf of the bean instance.For each bean instance, the container automaticallygenerates a proxy called an EJB object.The EJB object has access to all the functionality ofthe container such as JNDI registry, security,transaction management, thread pools, sessionmanagement.The EJB object is aware of the bean configuration andwhat services the POJO is supposed to provide.
  • 3. The EJB object can “insert” container servicesto client requests as needed, includingmanaging all aspects of the bean lifecycle.All the service details are completelytransparent to the bean clients.The client interacts with the EJB objectthrough the business interface for sessionbeans.The EJB object or message endpoint sitsbetween the message provider and the beaninstance for MDBs.
  • 4. Ideally, EJB components should merelyhold business logic and never access thecontainer or use container servicesdirectly.All the services are overlaid on the beanthrough configuration.The EJBContext interface allows directprogrammatic access to services such astransaction and security, which aretypically specified through configurationand completely managed by the container.
  • 5. public interface EJBContext {public Principal getCallerPrincipal();public boolean isCallerInRole(String roleName);public EJBHome getEJBHome();public EJBLocalHome getEJBLocalHome();public boolean getRollbackOnly();public UserTransaction getUserTransaction();public void setRollbackOnly();public TimerService getTimerService();public Object lookup(String name);}
  • 6. Methods DescriptiongetCallerPrincipalisCallerInRoleThese methods are useful when using in bean-managedsecurity.getEJBHomegetEJBLocalHomeThese methods are used to obtain the bean’s“remote home” and “local home” interfaces.getRollbackOnly,setRollbackOnlyThese methods are used for EJB transactionmanagement in the case of container-managedtransactions.getUserTransaction This method is used for EJB transaction managementin the case of bean-managed transactionsgetTimerService This method is used to get access to the EJB timerservice.lookup This method is used to get references to objects storedin the JNDI registry
  • 7. The session bean–specific subclass isjavax.ejb.SessionContext, and the MDB-specificsubclass is javax.ejb.MessageDrivenContext.
  • 8. EJBContext can be accessed through DI.The SessionContext adds a number of methods specific to thesession bean environment.The getEJBLocalObject and getEJBObject methods are meant forEJB 2 beans and will generate exceptions if used with EJB 3beans.MessageDrivenContext adds no methods specific to MDB andthrows exceptions if the isCallerInRole, getEJBHome, orgetEJBLocalHome methods are called.It is illegal to inject a MessageDrivenContext into a session beanor a SessionContext into an MDB.@MessageDrivenpublic class OrderBillingMDB {@Resource MessageDrivenContext context; }
  • 9. The container uses the explicitly specified nameparameter to figure out what resource to inject.The value of the name parameter in @Resource (orres-ref-name) is translated to a fully qualified JNDImapping in the form java:comp/env/[value of thename parameter].If the name element in the @Resource annotation isnot specified, the JNDI name for the resource will be ofthe form java:comp/env/ [bean class name includingpackage]/[name of the annotated field/property].EJB 3 essentially assumes that all JNDI names used incode are local references instead of global JNDI namesand automatically prepends names with thejava:comp/env/ prefix.
  • 10. Many application servers automatically resolve theenvironment naming context name to the global JNDI nameif a resource with the same global JNDI name exists.Application servers allow you to explicitly specify a globalJNDI name using the mappedName parameter of the@Resource annotation.@Resource(name="jdbc/ActionBazaarDS",mappedName="java:/DefaultDS")private javax.jdbc.DataSource myDB;Using the mappedName parameter makes code lessportable, hence use of deployment descriptors for mappingglobal JNDI names is preferred instead.The container resolves the JNDI references to the resourcesand binds the resource to the ENC during deployment.
  • 11. The @Resource annotation can also be applied to settermethods, and even classes along with instance variables.The setter injection relies on JavaBeans property-namingconventions, with instance variables being private and, gettersand setter non-private.@Statelesspublic class PlaceBidBean implements PlaceBid {private DataSource dataSource;@Resource(name="jdbc/actionBazaarDB")public void setDataSource(DataSource dataSource) {this.dataSource = dataSource;}
  • 12. The optional type parameter of the @Resourceannotation can be used to explicitly set the type ofthe injected resource.If omitted, the type of the injected resource isassumed to be the same as the type of the instancevariable or property.The type element is mandatory when the @Resourceannotation is used at the class level and uses JNDI toobtain a reference to the resource@Resource(name="jdbc/actionBazaarDB",type=javax.sql.DataSource.class)private DataSource dataSource;
  • 13. DI is supported only in the managed classes and cannot beused for injection in helper or utility classes.In the helper classes, the resource is look up using JNDI.1) Reference resource in EJB class:@Resource(name="jdbc/actionBazaarDB",mappedName="jdbc/actionBazaarDS", type=javax.sql.DataSource.class)@Statelesspublic class PlaceBidBean implements PlaceBid2) Look up the resource either from the EJB or the helper class:Context ctx = new InitialContext();DataSource ds = (DataSource)ctx.lookup("java:comp/env/jdbc/ActionBazaarDB")
  • 14. Parameter Type Description Defaultauthentication-TypeenumAuthentication-Type {CONTAINER,APPLICATION}The type of authenticationrequired for accessing theresource. The CONTAINER valuemeans that the container’s securitycontext is used for the resource.The APPLICATION value meansthat authentication for theresource must be provided by theapplication.CONTAINERshareable boolean Specifies whether the resource canbe shared.truedescription String The description of the resource. ""mappedName String A vendor-specific name that theresource may be mapped to, asopposed to the JNDI name.""
  • 15. The EJB context instance variable to beinjected is not stored in JNDI.When the container detects the@Resource annotation on the contextvariable, it figures out that the EJBcontext specific to the current beaninstance must be injected by looking atthe variable data type,javax.ejb.SessionContext or parent datatype, javax.ejb.EJBContext.
  • 16. Environment entries are essentially meant to be robustapplication constants and support a relatively small range of datatypes.Environment entries are specified in the deployment descriptorand are accessible via JNDI.<env-entry><env-entry-name>censorship</env-entry-name><env-entry-type>java.lang.Boolean</env-entry-type><env-entry-value>true</env-entry-value></env-entry>Since environment entries are accessible via JNDI they can beinjected by name.The data types of the environment entry and the injected variablemust be compatible.@Resource(name="censorship") private boolean censorship;
  • 17. JavaMail Sessions abstract the e-mail server configuration andcan be stored in the application server JNDI registry.The Session can be injected into an EJB (with the @Resourceannotation and name parameter specifying JNDI name).The container-managed timer service gives EJBs the ability toschedule tasks.The timer service is not saved in JNDI, but the containerresolves the resource by looking at the data type of theinjection target.The one DI feature glaringly missing is the ability to injectresources into POJOs and to inject POJOs that are not EJBs.An EJB bean class may inherit from another EJB class or a POJO.If the superclass defines any dependencies on resources usingthe @Resource annotation, they are inherited by the subclass.
  • 18. There are two ways of using programmatic lookups—using either theEJB context or a JNDI initial context.Any object stored in JNDI using the EJBContext.lookup method(including session bean references).Lookups compared to DI allows to determine which resource to usedynamically at runtime instead of being constrained to using staticconfiguration.DI and lookup using the EJB context are only available inside the JavaEE container.Basic method of looking up JNDI outside a container:Context context = new InitialContext();BidderAccountCreator accountCreator= (BidderAccountCreator)context.lookup("java:comp/env/ejb/BidderAccountCreator");accountCreator.addLoginInfo(loginInfo);accountCreator.createAccount();
  • 19. @EJB(name="ejb/BidderAccountCreator",beanInterface =BidderAccountCreator.class)@Statelesspublic class GoldBidderManagerBean implementsGoldBidderManager {@Resource SessionContext sessionContext;BidderAccountCreator accountCreator =(BidderAccountCreator)sessionContext.lookup("ejb/BidderAccountCreator");accountCreator.addLoginInfo(loginInfo);accountCreator.createAccount();
  • 20. EJB 3 interceptors are triggered at the beginning of a method and arearound when the method returns;They can inspect the method return value or any exceptions thrown by themethod.Interceptors can be applied to both session and message-driven beans.@Statelesspublic class PlaceBidBean implements PlaceBid {@Interceptors(ActionBazaarLogger.class)public void addBid(Bid bid) { }}public class ActionBazaarLogger {@AroundInvokepublic Object logMethodEntry(InvocationContext invocationContext) throws Exception {System.out.println(invocationContext.getMethod().getName());return invocationContext.proceed(); }}
  • 21. The @Interceptors annotation allows you to specifyone or more interceptor classes for a method or class.When the @Interceptors annotation is applied to anentire class, the interceptor is triggered if any of thetarget class’s methods are invoked.The @Interceptors annotation allows to attach morethan one interceptor either at a class or method levelby using a comma-separated list as a parameter to theannotation.@Interceptors({ActionBazaarLogger.class,BidStatisticsTracker.class})public class PlaceBidBean { ... }
  • 22. A default interceptor is essentially a catchall mechanism thatattaches to all the methods of every bean in the EJB module.The interceptors are called from the larger scope to the smallerscope with the default interceptor triggered first, then theclass-level interceptor, and finally the method level interceptor.<assembly-descriptor><interceptor-binding><ejb-name>*</ejb-name><interceptor-class>actionbazaar.buslogic.ActionBazaarLogger</interceptor-class></interceptor-binding></assembly-descriptor>
  • 23. If more than one interceptor is applied at any given level,they are executed in the order in which they are specified.Applying the @javax.interceptor.Exclude-DefaultInterceptors annotation on either a class or a methoddisables all default interceptors on the class or method.Similarly the @javax.interceptor.Exclude- ClassInterceptorsannotation disables class-level interceptors for a method.@Interceptors(ActionBazaarLogger.class)@ExcludeDefaultInterceptors@ExcludeClassInterceptorspublic void addBid (...
  • 24. Interceptor must always have only one method that is designatedas the around invoke (AroundInvoke) method.Around invoke methods must not be business methods.An around invoke method (with @AroundInvoke annotation) isautomatically triggered by the container when a client invokes amethod that has designated it to be its interceptor.Any method designated AroundInvoke must follow the pattern:Object <METHOD>(InvocationContext) throws ExceptionThe call to proceed method of InvocationContext interface tellsthe container that it should proceed to the next interceptor in theexecution chain or call the intercepted business method.If a business method interceptor throws an exception beforeinvoking the proceed method, the processing of otherinterceptors in the invocation chain and the target businessmethod will be terminated.
  • 25. public interface InvocationContext {public Object getTarget();public Method getMethod();public Object[] getParameters();public void setParameters(Object[]);public java.util.Map<String,Object> getContextData();public Object proceed() throws Exception;}The getTarget method retrieves the bean instance that the intercepted methodbelongs to.The getMethod method returns the method of the bean class for which theinterceptor was invoked.The getParameters method returns the parameters passed to the intercepted methodas an array of objects.The setParameters method allows us to change these values at runtime before theyare passed to the method.The InvocationContext.getContextData method enables to access the contexts that areshared across the interceptor chain for a given method, inorder to communicatebetween interceptors using the data attached to an InvocationContext.The invocation context data is simply a Map used to store namevalue pairs.
  • 26. Lifecycle callbacks defined in an interceptor class are knownas lifecycle callback interceptors or lifecycle callbacklisteners.When the target bean transitions lifecycles, annotatedmethods (@PostConstruct, @PrePassivate, @PostActivate,and @PreDestroy) in the interceptor class are triggered.Lifecycle interceptor methods cannot throw checkedexceptions.A bean can have the same lifecycle callbacks both in thebean itself as well as in one or more interceptors.The InvocationContext proceed method in lifecycleinterceptor methods ensures that the next lifecycleinterceptor method in the invocation chain or the beanlifecycle method is triggered.
  • 27. Feature Lifecycle Callback Business MethodInvocation Gets invoked when a lifecycleevent occurs.Gets invoked when a business methodis called by a client.Location In a separate Interceptor class orin the bean classIn the class or an interceptor class.Methodsignaturevoid<METHOD>(InvocationContext) in a separate interceptor class.void <METHOD>()–in bean class.Object <METHOD>(Invocation-Context) throws ExceptionAnnotation @PreDestroy, @PostConstruct,@PrePassivate, @PostActivate@AroundInvokeExceptionhandlingMay throw runtime exceptions butmust not throw checkedexceptions. May catch and swallowexceptions. No other lifecyclecallback methods are called if anexception is thrown.May throw application or runtimeexception. May catch and swallowruntime exceptions. No other businessinterceptor methods or the businessmethod itself are called if an exception isthrown before calling proceed method.Transaction& securitycontextNo security and transactioncontext.Share same security & transactioncontext within which the originalbusiness method was invoked.
  • 28. The EJB 3 timer service allows to specify a method(called the timeout method) that is automaticallyinvoked by the container after a specified interval oftime.The timer service can be used to register for callbackstriggered once at a specific time or at regular intervals.Timers can only be used in stateless session beans andMDBs because of their asynchronous, stateless nature.Timers are persistent and can survive a container crashor restart.Timers are transactional, that is, a transaction failure ina timeout method rolls back the actions taken by thetimer.
  • 29. public class PlaceBidBean implements PlaceBid {...@Resource TimerService timerService;...public void addBid(Bid bid) {... Code to add the bid ...timerService.createTimer(15*60*1000, 15*60*1000, bid);...}...@Timeoutpublic void monitorBid(Timer timer) {Bid bid = (Bid) timer.getInfo();... Code to monitor the bid ...}}
  • 30. The EJB timer service can be injected intoa Java EE component using the @Resourceannotation.The EJB container timer service can also beaccessed through the EJB context.@Resource SessionContext context;TimerService timerService =context.getTimerService();
  • 31. public interface javax.ejb.TimerService {public Timer createTimer(long duration,java.io.Serializable info);public Timer createTimer(long initialDuration, longintervalDuration, java.io.Serializable info);public Timer createTimer(java.util.Date expiration,java.io.Serializable info);public Timer createTimer(java.util.DateinitialExpiration, long intervalDuration,java.io.Serializable info);public Collection getTimers();}
  • 32. The first createTimer method allows to create a single-eventtimer that is fired only once and not repeated.The first parameter, duration, specifies the time in millisecondsafter which the method should be invoked.The second parameter, info, allows to attach an arbitrary pieceof information to the timer, and must be always Serializable.The second createTimer method allows to create recurringtimers with initial timeout and interval durations set inmilliseconds.The third version allows to create a timer that fires once andonly once with value of expiration time as a specific instant intime represented by a java.util.Date instead of a long timeoffset.The fourth version is similar to second version of thecreateTimer method, using a concrete date instead of an offsetfrom the current time.The getTimers method retrieves all of the active Timersassociated with the current EJB.
  • 33. The @Timeout annotation is used to specify the designatedtimeout method.the @Timeout annotation has convention as:void <METHOD>(Timer timer)A bean can have at most one timeout method, which can bespecified (through annotation @Timeout or deploymentdescriptor timeout-method) either on the bean class or on asuperclass.If the bean class implements the javax.ejb.TimedObjectinterface, the ejbTimeout method is the bean’s timeoutmethod.The Timer for which the callback was invoked is passed in as aparameter for the method as processing context becausemultiple Timers may invoke the same timeout method.
  • 34. public interface javax.ejb.Timer {public void cancel();public long getTimeRemaining();public java.util.Date getNextTimeout();public javax.ejb.TimerHandle getHandle();public java.io.Serializable getInfo();}
  • 35. The cancel method is useful in canceling a timer prior toits expiration.The getTimeRemaining method is used on either a single-use or interval timer and returns the remaining time forthe timer to expire, in milliseconds.The getNextTimeout method indicates the next time arecurring Timer will time out, as a java.util.Date instead ofa long time offset.The getHandle method returns a javax.ejb.TimerHandle,which is a serialized object to store and to obtaininformation about the Timer.The getInfo method is useful in writing nontrivial timeoutfunctions and accessing extra processing informationattached to the Timer by the bean method creating theTimer.
  • 36. EJB Timers are transactional objects and on anruntime exception in the timeout method, the timercreation is undone.The timeout method can be executed in atransactional context.A transactional attribute can be specified for thetimeout method—Required or RequiresNew—and thecontainer will start a transaction before invoking thetimeout method.If the transaction fails, the container will make surethe changes made by the failed method do not takeeffect and will retry the timeout method.
  • 37. Timers are part of the EJB specification and portable acrosscontainers.EJB timer service comes as a standard part of a Java EE applicationserver involving no extra cost and config.The timer is a container-managed service and hence likely to havebetter out-of-the-box performance.Transactions are fully supported with timers.By default, EJB timers are persisted and survive EJB lifecycles andcontainer restarts.EJB timers are not meant for realtime applications where precisiontiming is absolutely critical.EJB timers lack support for extremely flexible cron-type timers,blackout dates, workflow modeling for jobs etc.There is no robust GUI admin tool to create, manage, and monitorEJB 3 timers.
  • 38. A transaction is a grouping of tasks that must be processed asan inseparable unit.Every task that is part of the transaction must succeed in orderfor the transaction to succeed.ACID stands for atomicity, consistency, isolation, and durability.Atomicity: Transactions are atomic in nature; they eithercommit or roll back together.Consistency: If the system is in a state consistent with thebusiness rules before a transaction begins, it must remain in aconsistent state after the transaction is rolled back orcommitted.Isolation: The isolation property makes sure transactions donot step on one another’s toes. Handled by transactionmanager by placing some kind of lock on the data accessed bya transaction.Durability: Durability means that a transaction, oncecommitted, is guaranteed to become permanent, implementedusing transaction logs.
  • 39. Read uncommitted—At this isolation level, thetransaction can read the uncommitted data of othertransactions, also known as a “dirty” read. One should notuse this level in a multithreaded environment.Read committed—The transaction will never readuncommitted changes from another transaction. This isthe default level for most databases.Repeatable read—The transaction is guaranteed to getthe same data on multiple reads of the same rows untilthe transaction ends.Serializable—This is the highest isolation level andguarantees that none of the tables you touch will changeduring the transaction, including adding new rows. Thisisolation level is very likely to cause performancebottlenecks.
  • 40. In enterprise transaction management, thecomponent that takes care of transactions for aparticular resource is called a resource manager.A resource can be database or a message server.A transaction that uses a single resource is called alocal transaction.The transaction manager is a component thatcoordinates a single transaction over multipledistributed resources.The transaction manager coordinates applicationrequests among multiple resource managers, andeach transaction phase may translate to numerouslow-level resource commands issued by the resourcemanagers.
  • 41. The two-phase commit protocol performs anadditional preparatory step before the final commit.During this step, each resource manager involved isasked if the current transaction can be successfullycommitted.If any of the resource managers indicate that thetransaction cannot be committed if attempted, theentire transaction is abandoned (rolled back).Otherwise, the transaction is allowed to proceed andall resource managers are asked to commit.Only distributed transactions use the two-phasecommit protocol.
  • 42. It enables to declaratively, done throughannotations or the deployment descriptor.In a CMT, the container starts, commits, androlls back a transaction on our behalf.Transaction boundaries in declarativetransactions are always marked by the start andend of EJB business methods.By default, the container assumes to use CMTon all business methods.
  • 43. @Stateless@TransactionManagement(TransactionManagementType.CONTAINER)public class OrderManagerBean {@Resourceprivate SessionContext context;@TransactionAttribute(TransactionAttributeType.REQUIRED)public void placeSnagItOrder(Item item, Customer customer){try {if (!bidsExisting(item)){validateCredit(customer);chargeCustomer(customer, item);removeItemFromBidding(item);}} catch (CreditValidationException cve) {context.setRollbackOnly();} catch (CreditProcessingException cpe){context.setRollbackOnly();} catch (DatabaseException de) { context.setRollbackOnly(); }}}
  • 44. The @TransactionManagement annotation specifieswhether CMT or BMT is to be used for a particularbean.TransactionManagementType.CONTAINER means thecontainer should manage transactions on the bean’sbehalf.TransactionManagementType.BEAN enables to tomanage transactions programmatically.If we do not specify the @TransactionManagementannotation or the transactiontype element in thedeployment descriptor, the container assumes thatwe intend to use a CMT.
  • 45. It enables to tell the container how it shouldmanage transactions.The transaction wraps around the bean’smethod could be started by the containerspecifically when calling the method, or itcould be inherited from a client calling themethod.The annotation can be applied either toindividual CMT bean methods or to the entirebean.If the @TransactionAttribute annotation is
  • 46. TransactionAttributeCaller TransactionExists?EffectREQUIRED No Container creates a new transaction.Yes Method joins the caller’s transaction.REQUIRES_NEW No Container creates a new transaction.Yes Container creates a new transaction andthe caller’s transaction is suspended.SUPPORTS No No transaction is used.Yes Method joins the caller’s transaction.MANDATORY No javax.ejb.EJBTransactionRequired-Exception is thrown.Yes Method joins the caller’s transaction.NOT_SUPPORTED No No transaction is used.Yes The caller’s transaction is suspended and themethod iscalled without a transaction.NEVER No No transaction is used.Yes javax.ejb.EJBException is thrown.
  • 47. REQUIRED: It is a default value and specifies that the EJBmethod must always be invoked within a transaction.If the method is invoked from a nontransactional client thecontainer will start a transaction before the method is calledand finish it when the method returns.If the caller invokes the method from a transactional context,the method will join the existing transactionREQUIRES_NEW: This value indicates that the container mustalways create a new transaction to invoke the EJB method.If the client already has a transaction, it is temporarilysuspended (paused) until our method returns and thenresumed.The success or failure of the new transaction has no effect onthe existing client transaction.
  • 48. SUPPORTS: It essentially means the EJB method will inheritwhatever the transactional environment of the caller is.If the caller does not have a transaction, the EJB method willbe called without a transaction.If the caller is transactional, the EJB method will join theexisting transaction and won’t cause the exiting transaction tobe suspended.MANDATORY: It means requires existing—that is, the callermust have a transaction before calling an EJB method and thecontainer should never create a transaction on behalf of theclient.If the EJB method using the MANDATORY attribute is invokedfrom a nontransactional client, the container throws anEJBTransactionRequiredException.
  • 49. NOT_SUPPORTED: When assigned this transactionattribute, the EJB method cannot be invoked in atransactional context.If a caller with an associated transaction invokes themethod, the container will suspend the transaction,invoke the method, and then resume the transactionwhen the method returns. Used for MDBs.NEVER: This attribute means that the EJB method cannever be invoked from a transactional client.If such an attempt is made, a javax.ejb.EJBException isthrown.
  • 50. The transaction is never rolled backimmediately, but a flag is set for the containerto do the actual rollback when it is time to endthe transaction.The getRollbackOnly method returns a booleantelling whether the underlying CMT transactionhas already been marked for rollback.The setRollbackOnly and getRollbackOnlymethods can only be invoked in an EJB usingCMT with these transaction attributes:REQUIRED, REQUIRES_NEW, or MANDATORY.
  • 51. Transactional outcome is controlled through the@javax.ejb.ApplicationException annotation to avoid the all-too-common exception handling code.The @ApplicationException annotation identifies a Javachecked or unchecked exception as an application exception.By default, all checked exceptions except forjava.rmi.RemoteException are assumed to be applicationexceptions and handled by the method invoker.All exceptions that inherit from eitherjava.rmi.RemoteExceptions or java.lang.RuntimeException areassumed to be system exceptions are not passed to the clientas it is but are wrapped in a javax.ejb.EJBException instead.Setting the rollback element to true (default is false) tells thecontainer that it should roll back the transaction before theexception is passed on to the client.
  • 52. public void placeSnagItOrder(Item item, Customer customer)throws CreditValidationException,CreditProcessingException, DatabaseException {if (!bidsExisting(item)){ …… }}...@ApplicationException(rollback=true)public class CreditValidationException extends Exception { …. }...@ApplicationException(rollback=true)public class CreditProcessingException extends Exception { … }...@ApplicationException(rollback=false)public class DatabaseException extends RuntimeException { … }
  • 53. CMT notifies about the transaction’s lifecycle events.CMT bean implements thejavax.ejb.SessionSynchronization interface whichdefines three methods:void afterBegin()—Called right after the containercreates a new transaction and before the businessmethod is invoked.void beforeCompletion()—Invoked after a businessmethod returns but right before the container ends atransaction.void afterCompletion(boolean committed)—Calledafter the transaction finishes. The boolean committedflag indicates whether a method was committed orrolled back.
  • 54. @Stateless)@TransactionManagement(TransactionManagementType.BEAN)public class OrderManagerBean {@Resourceprivate UserTransaction userTransaction;public void placeSnagItOrder(Item item, Customer customer){try {userTransaction.begin();if (!bidsExisting(item)){validateCredit(customer);chargeCustomer(customer, item);removeItemFromBidding(item);}userTransaction.commit();} catch (CreditValidationException cve) { userTransaction.rollback();} catch (CreditProcessingException cpe){ userTransaction.rollback();} catch (DatabaseException de) { userTransaction.rollback();} catch (Exception e) { e.printStackTrace();}}}
  • 55. The UserTransaction interface encapsulates the basicfunctionality provided by a Java EE transaction manager.The UserTransaction can be accessed in by injecting itthrough the @Resource annotation.The application server can bind the UserTransaction to theJNDI name java:comp/ UserTransaction, and usedcontext.lookup("java:comp/UserTransaction") method toacccess the UserTransaction.UserTransaction can be access from thegetUserTransaction method of the EJBContext (eitherSessionContext or MessageDrivenContext) only whenusing BMT.The methods getRollbackOnly and setRollbackOnly ofEJBContext cannot be used in BMT causing container tothrow an IllegalStateException.
  • 56. public interface UserTransaction {void begin() throws NotSupportedException,SystemException;void commit() throws RollbackException,HeuristicMixedException, HeuristicRollbackException,SecurityException, IllegalStateException, SystemException;void rollback() throws IllegalStateException,SecurityException, SystemException;void setRollbackOnly() throws IllegalStateException,SystemException;int getStatus() throws SystemException;void setTransactionTimeout(int seconds) throwsSystemException;}
  • 57. The begin method creates a new low-level transactionbehind the scenes and associates it with the currentthread.The commit and rollback methods, on the other hand,remove the transaction attached to the currentthread by using the begin method.The getStatus method returns an integer-based statusof the current transactions, indicating a more fine-tuned set of states a transaction could possibly be in.The javax.transaction.Status interface defines thetransaction states.The setTransactionTimeout method specifies thetime, in seconds, in which a transaction must finish.
  • 58. Status DescriptionSTATUS_ACTIVE transaction is in an active stateSTATUS_MARKED_ROLLBACK transaction is marked for rollbackSTATUS_PREPARED transaction is in the prepared state because allresources have agreed to commitSTATUS_COMMITTED associated transaction has been committedSTATUS_ROLLEDBACK associated transaction has been rolled backSTATUS_UNKNOWN status for associated transaction is not knownSTATUS_NO_TRANSACTION no associated transaction in the current threadSTATUS_PREPARING associated transaction is preparing to be committed andawaiting response from subordinate resourcesSTATUS_COMMITTING transaction is in the process of committingSTATUS_ROLLING_BACK transaction is in the process of rolling back
  • 59. BMT transactions need not begin and end in theconfines of a single method call, hence useful tomaintain a transaction across method calls.(Though this is error prone and not preferredapproach.)BMT enables to fine-tune the transactionboundaries so that the data held by the code isisolated for the shortest time possible.Drawback of BMT is the fact that it can never joinan existing transaction.Existing transactions are always suspended whencalling a BMT method, significantly limiting flexiblecomponent reuse.