JavaEnterprise Edition (Java EE) refers to an umbrella specification thatgroups 79 API specifications (as of Java EE 5) designed for enterprisecomputing applications such as transaction processing. Java EE APIfeatures work together to provide a complete environment for developingand deploying TP applications, including:
The Swing Library, Servlets, Java Server Pages, and Java Server Faces for developing front-end programs, including interactive menu and forms capabilities for web browsers and native PC and UNIX programs
Enterprise Java Beans (EJBs), a distributed computing component model for developing request controllers and transaction servers that support a variety of front-end programs
The Java Persistence API (JPA), a lightweight object-relational mapping integrated with EJBs to interact with persistent entities stored in a relational database
The Java Connector Architecture (JCA) API, a programming environment for integration with legacy systems that includes a standard client and adapter toolkit
The Java Transaction API (JTA), an infrastructure and programming environment for transaction management, used in both the implicit and explicit programming models for Java EE
A WS-BPEL engine for business process management, which is also provided by most Java EE vendors
JavaEE is defined through the Java Community Process, a consortium of Javavendors chaired by Sun Microsystems. Java EE originally was released inDecember 1999, and has gone through several iterations since then. Itsoriginal name was Java 2 Enterprise Edition, or J2EE, which was changedto Java EE as of its fourth release, called Java EE 5. A majordifference between the enterprise edition and the standard edition ofJava is the addition of EJBs. The current version, EJB3, represents asignificant change from earlier versions of EJB (1.1 through 2.1), witha lighter weight container, JPA in place of entity beans, and the useof Java 5 annotations for transaction demarcation and other EJBfunctions.
JavaEE APIs are delivered in Java-EE-compliant application server productsfrom IBM, Oracle, Red Hat, and others. Java-EE-compliant vendors mustpass a set of conformance tests to receive a certification from theJava Community Process, which indicates that the vendor hassuccessfully implemented each of the required APIs. Examples ofcertified products include IBM’s WebSphere Application Server, Oracle’sWebLogic Application Server, and Red Hat’s JBoss Application Server.These products are available on UNIX, Windows, and zOS operatingsystems. Java-EE-compliant application servers typically includevendor-specific mechanisms for server clusteringand failover, sometimes including state caching and replication.However, these features are not included in the Java EE APIs and aretherefore beyond the scope of this book.
Incontrast to the Microsoft transactional middleware, which runs only onWindows operating systems, Java-based transactional middleware runs onvirtually any operating system. But operating system portability hasits costs. In particular, .NET Framework components are generallybetter integrated with the operating system than Java-based components.As might be expected, the specific details of how to create and deploytransactional programs with Java EE and the .NET Framework aredifferent, even though the technologies and underlying concepts arevery similar.
Figure 10.15illustrates the relationships among the transactional middlewarecomponents of the Java EE architecture. It includes two types offront-end programs, those designed to run in a web browser and thosedesigned to run on a desktop PC or UNIX system. The Java EEarchitecture is very similar to the .NET Framework in this respect, buta significant difference is the presence of EJBs, which are programsand associated containers that were specifically designed for use in TPapplications.
Typically,a browser-based front-end program communicates with the web tier, whichin turn calls the EJB tier. The EJB tier then invokes one or more JPAentities at the persistence tier. An EJB may also use JCA to invoke aback-end system, such as a legacy TP monitor, or may directly access adatabase using SQL commands through Java Database Connectivity (JDBC).
Thestandard protocol for remote communication between the web tier and theEJB tier is the Java Remote Method Invocation over the CORBA InternetInter-Orb Protocol (RMI/IIOP). Other communication protocols can alsobe used. SOAP over HTTP is supported from a Web Services client to theEJB tier. Java EE vendors typically offer proprietary communicationsprotocols and data formats specifically tuned for their individualproducts. It is also fairly common practice for the web tier tocommunicate locally with the EJB tier.
Anapplication developed using Java-EE-compliant transactional middlewarecomponents can therefore implement a two-tier, three-tier, or multitierarchitecture to meet scalability, availability, and other TPapplication requirements. For example:
When a web browser is used for the front-end program, a web server can function as the request controller by including an EJB that routes the request to a transaction server program.
When a PC- or UNIX-based front-end program is used, the EJB tier can be used to fulfill the request controller function on its own, without a web server.
When multiple tiers are needed, EJBs can be used to fulfill both the request controller and transaction server functions (including the persistence tier).
Stored procedures can also fulfill the transaction server function for web server hosted or plain EJB-based request controllers.
Asin the .NET environment, both implicit and explicit transactionprogramming models are supported, and the implicit model is recommendedfor most applications.
In Java EE the technologies used for front-end programs include:
The Swing Library for PC- and UNIX-based GUIs
Servlets, Java Server Pages (JSP), and Java Server Faces (JSF) for web browser-based GUIs
Swingis the name of a collection of libraries and functions used to develophighly interactive PC- and UNIX-based front-end programs. The SwingLibrary is comparable to the .NET Framework’s WPF and Silverlight.Library functions define a screen’s area and layout, menus, scrollbars, tabs, buttons, sliders, tables, frames, toolbars, and so on. Theexample in Figure 10.16uses the Swing libraries to display a table of information. As shown inthe figure, Swing classes can be used to construct a variety of GUIfeatures. In this case theJTable class isused to create a table of a customer’s accounts. Although the mainprogram thread exits at the end of the example, Swing supplies a secondthread that continues processing in the background to handle GUIcomponents.
import java.awt.*; |
A Java servletextends the capability of a standard web server to support dynamiccontent generation. The Java Servlet API is an alternative to webserver callout mechanisms such as Common Gateway Interface (CGI)scripts and web server APIs such as Apache API or ISAPI (IIS). Servletshandle HTTP sessions and route requests to Java objects, EJBs, ordatabases. Servlets also handle REST and Web Services communications.The server can use any technique to maintain session state, typicallyusing cookies or URL rewriting. All Java-EE-based application serverproducts include a servlet engine. Apache Tomcat is an example of apopular standalone servlet engine.
Java Server Pages (JSP)layer on servlets and replace static HTML and XML pages with dynamiccontent generated using JSP tags embedded in HTML or XML pages. Thetags access and generate content that is then formatted into HTML orXML. When the page request is executed, a JSP is converted to a servletfor handling the content to be displayed in the browser.
The example in Figure 10.17illustrates the use of JSP tags to generate information within an HTMLbulleted list. When executed, the JSP tags dynamically generate thecontent for the bank name, the account balance, and the current date ofthe web server access. Java Server Faces (JSF)components are server-side controllers of browser-based menu and formcomponents such as buttons, tables, and graphics. JSF and JSPtechnologies can work together, for example when JSFs are used tocreate JSPs, and JSPs generate content for JSF-defined menu and formelements. JSPs and JSFs can work in combination to drive server-sideand client-side user interaction scenarios. For example, the JSF customlibrary can be used by the JSP to generate content and GUI elements forthe browser.
<UL> |
The example in Figure 10.18illustrates a simple form defined using JSF tag libraries. The JSFcomponent classes maintain the component’s state and the rendering tagsdefine how to render the content for the user. For example, thecommandButtontag is rendered as a button. The example also illustrates a validationfunction to check a username when the button is clicked. When a JSP iscreated using JSF, a tree of components is mapped into memory fromwhich a response to a browser request is generated.
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %> |
RESTsupport in Java EE environments is provided by the Java API for RestfulWeb Services (JAX-RS). JAX-RS defines a set of annotations andinterfaces that can be used in Java objects to expose them as RESTfulweb resources. JAX-RS objects can be deployed to either a standaloneservlet engine or a servlet engine within a Java EE application server.JAX-RS enables front-end programs to call the objects using HTTP as thenetwork protocol, using HTTP content types to define the data formats.
An Enterprise Java Bean (EJB)refers both to a type of Java program designed for TP applications andto a container within which such a program is deployed. An EJBabstracts transactional middleware functionality, such as threading,transaction control, and security. EJBs originally were designed forcompatibility with legacy TP monitors, although the most popularimplementations of EJBs have been written from scratch. EJBs haveevolved significantly from their initial definition. Compared to EJB2,EJB3 beans feature a lighter weight container, dependency injection,and Java 5 attributes for expressing configuration properties.
InJava EE, a request controller can be developed for the web tier or theEJB tier. When developed for the web tier, the request controllertypically is implemented using a servlet engine running inside a webserver, which routes the request to an EJB. The EJB can execute in theweb server or in a separate process.
EJB types include:
Session beans: Designed for hosting an interactive session with the front-end program. A session bean can be stateless or stateful and can manage transactions.
Message-driven beans: Designed for interacting with asynchronous messaging systems that conform to the Java Messaging Service (JMS) API.
EJB2defined a third EJB type, an entity bean. Entity beans are preserved inEJB3 for compatibility with EJB2 applications. In EJB3, entity beansare replaced by JPA entities (covered next and in Section 10.6).
AnEJB can manage transactions and participate in transactionalcompositions. A message-driven bean can also manage transactions, butcannot be composed into a transaction started by another bean.
Asession bean is allocated to a single instance of a front-end programand is terminated when the front-end program terminates. A statefulsession bean maintains the state of its instance variables for theduration of its interaction with the front-end program; a statelesssession bean does not.
Statefulsession bean state is volatile and not transactional. For a web browserfront-end program, session state management also can be provided by theHttpSession object. For PC- orUNIX-based Swing clients stateful session beans are the only mechanismavailable to preserve in-memory conversational state across multipleinteractions between the front-end program and the request controller.
Aswith any stateless design, the advantage of a stateless session bean isthat the application server can maintain a reusable pool of statelesssession beans, allocate them to any request on demand, and deallocatethem once a bean finishes executing the request. With a stateful beanthe application server has to direct a subsequent call by a givenfront-end program to the same bean instance so that it has access tothe state of its conversation with the front end.
Astateless session bean can have a Web Service interface, allowing a WebService client to invoke an EJB method. Web Services support isincluded in the Java EE specifications through the inclusion of theJava API for XML-Based Web Services (JAX-WS) specification. Therefore,all Java-EE-complaint application server products offer toolkits thatgenerate a Web Service interface from an EJB interface.
Asession bean can query and update a relational database by using one ormore JPA entities. The data members of a JPA entity are transactionallypersistent, and a session bean can access that state by issuingoperations on the JPAEntityManager.Like a web server, however, a session bean also has the option toaccess a database directly to execute embedded SQL or to invoke astored procedure using JDBC. Direct database access is commonly used inpractice.
A bean implementation class is an ordinary Java class file that contains the method implementations for the EJB. An implementation class exposes a business interfacefor remote and local access to business logic methods. Restrictions onthe Java class and methods used for an EJB ensure that everything workscorrectly when deployed within a container, such that they must bepublic, cannot be final, and cannot be abstract.
Abean implementation class becomes an EJB by importing one or more EJBlibraries and either including one or more EJB annotations or declaringit an EJB in an associated descriptor file (see Figure 10.24).EJB annotations control the abstractions of the container and generatedeployment metadata. As of EJB3 the embedded annotations can be used togenerate the descriptor file. As with entity beans, a manually codeddescriptor file (i.e., created without using annotations) is supportedfor backward compatibility with EJB2. In EJB3, the embedded annotationstypically are used to generate the deployment metadata, including anyvendor-specific variations.
The EJB type annotations are:
@javax.ejb.Stateless
@javax.ejb.Stateful
@javax.ejb.MessageDriven
Thefirst two define a session bean as being either stateless or stateful.The third defines a message-driven bean (i.e., one that interacts withJMS message queues). TheStateless annotation is more commonly used thanStateful. In EJB3, the@javax.ejb.entity annotation is used only to include an EJB 2.1 entity bean into an EJB3-compliant application server.
Otherannotations specify transaction control, security, and how to handlemessages and resources. Each of the annotations other than the EJB typehas a default value if not specified. For example, if a transactioncontrol annotation is not specified, the default is to require atransaction for each method in a class.
The example in Figure 10.19illustrates a stateless session bean for a group of methods that canperform several operations for a fictitious bank account managementapplication. A session bean typically is invoked by the servlet engine,although it can also be invoked using a Web Service, another EJB, or aSwing client. Since no@TransactionAttributeannotation is included, the bean uses default of container-managedtransactions with a transaction required for the execution of eachmethod. Thus, if a method is called from another method, the callingmethod’s transaction will be used. Otherwise a new transaction will becreated.
Code View: Scroll / Show All import javax.ejb.Stateless; |
An EJB referenceis needed to invoke a bean, with the exception of a Web Serviceinvocation of a stateless session bean method. The EJB reference can beinjected or retrieved using a directory lookup. A typical directoryservice for a Java EE-based application server is the Java Naming andDirectory Interface (JNDI). Figure 10.20 shows an example of a client with an EJB reference injected using the@EJB annotation to provide the reference that can be used to invoke theTransfer EJB. The@Resourceannotation also can be used to inject a variety of other externalinformation, such an environment variable, an EJB context, a JMSdestination, a connection factory, or a data source.
import javax.naming.Context; |
Thedefault for accessing an interface is local access; that is, from anEJB client running in the same address space. A remotely accessibleinterface needs to be explicitly identified using the@javax.ejb.Remote annotation. The@javax.ejb.Local annotation explicitly restricts an interface to local access.
The@TransactionManagement annotation defines whether the implicit or explicit programming model is used for a bean. Valid values for this attribute are:
TransactionManagementType.CONTAINER
TransactionManagementType.BEAN
When the value isCONTAINER the implicit programming model is used, which is called container managed in EJB terminology. When it’sBEAN, the explicit programming model is used, called bean managed.
The@javax.ejb.ApplicationExceptionannotation marks an application exception that can be thrown by amethod in a bean managed transaction. The exception is reporteddirectly to the EJB client when it occurs. The rollback attribute ofthe annotation can be used to define whether the exceptionautomatically causes a rollback.
The@TransactionAttributeis used to control the operations of the implicit programming model,such as whether or not the container is required to start a newtransaction before executing each method in the class. The next sectionlists the valid values for this attribute.
A JPA entity can be defined within an EJB to map its data to a relational database, using an object-relational mapping. The@javax.persistence.Entity annotation defines a Java class as a JPA entity. A JPA entity can be used from within a session bean or a plain Java class.
Inprevious versions of EJB this functionality was called bean-managed orcontainer-managed persistence. JPA is lighter weight, easier to use,and more efficient than the previous EJB approach. A JPA entity mapsthe data items and attributes of a Java class to one or more rows inone or more database tables. Optional attributes can be used to specifyfine-grained control over which data items are persisted.
The example in Figure 10.21 shows a stateless session bean that uses a JPAEntityManagerto create a new account record. Bean methods access and update thepersistent resource. Operations to create or update an entity shouldexecute in the context of a transaction, which is why the@TransactionAttribute annotation is set toREQUIRED. It creates a newAccount record based on parameters passed to thecreateAccount method, and then calls theem.persistmethod to add a row to the database table. When used in an EJB, a JPAentity participates in the global transaction managed by the JavaTransaction API (JTA; described later in this section). When usedoutside of an EJB, a JPA entity can use a JDBC managed transaction or aglobal transaction managed by JTA.
import javax.ejb.Stateless; |
Javadevelopers creating TP applications may choose to use a persistenceabstraction from a plain Java object or from within an EJB. If using aplain Java object, a session can be established with a single resourcemanager to directly control its transactions. If using a persistence abstraction within an EJB, JTA is used to control the transaction.
An EJB does not have an equivalent mechanism to the .NET Frameworkset.complete()method because an EJB is not treated as a transaction participant. Nordoes the EJB specification include a concept directly comparable to anambient transaction; that is, one that exists independently of thelifecycle of an object for which a transaction is started. However,Java EE does offer thesetRollbackOnly command for a subobject to tell the top-level object to abort.
Inthe implicit programming model the EJB container automatically startsand terminates a transaction when a transactional EJB method isinvoked. Successful completion commits the transaction and an exceptioncan be set to cause an automatic abort.
Bydefault, the EJB container automatically invokes a business methodwithin a transaction context and automatically decides whether tocommit or abort the transaction, depending on whether the methodcompletes successfully or not. A transaction annotation can bespecified on the entire bean class, or on individual methods tooverride the default behavior. An annotation at the method leveloverrides an annotation at the class level, if both are specified.
Valid values for the@TransactionAttribute annotation are:
REQUIRES_NEW
REQUIRED
SUPPORTS
NOT_SUPPORTED
MANDATORY
NEVER
The transaction attribute values instruct the container to perform the following operations:
REQUIRES_NEW. Every invocation of the method starts executing in a new transaction, whether or not the caller was already executing in a transaction.
REQUIRED. If the caller is already running within a transaction, then the called method executes within that transaction. If not, then the called method starts executing in a new transaction.
SUPPORTS. If the caller is already running within a transaction, then the called method executes within that transaction. If not, then the called method does not execute within a transaction.
NOT_SUPPORTED. The called method does not execute within a transaction, even if the caller is running within a transaction.
MANDATORY. If the caller is already running within a transaction, then the called method executes within that transaction. If not, an exception is raised.
NEVER. If the caller is already running within a transaction, an exception is raised.
If the transaction attribute of a message-driven bean isREQUIRED,then the bean executes as a top-level transaction. The transactionincludes its operations on the message queue and on any othertransactional resources. Operations in a message-driven bean cannotjoin the transactional operations of any other bean. When thetransaction attribute isNOT_SUPPORTED,the message-driven bean’s operations do not execute in the context of atransaction. A container-managed transaction is required to coordinateoperations on message queues with operations on other persistentresources.
An EJB always uses JTA unless theNOT_SUPPORTEDattribute is specified. JTA implementations use a one-phase commitoptimization whenever there’s a single resource manager. Thisoptimization is sufficient for most applications. However, unlike thePSPE optimization in .NET’ssystem.transactions,it still involves the application server’s transaction manager. Thereare workarounds, but they involve the EJB doing explicit transactioncontrol with the RM.
Figure 10.22 illustrates a session bean that uses theREQUIRED attribute to invoke two methods within the same transaction. TheREQUIREDattribute means that if the caller is executing in a transaction, thenany called methods also execute within the caller’s transaction. If thecaller is not executing a transaction, the method executes in a newtop-level transaction.
public class TransferBean implements Transfer { |
Anexception class can be defined so that when the execution of atransaction throws an exception, the application can catch it in theexception handler and throw an application-specific exception. In theexample in Figure 10.23 the@ApplicationException annotation sets therollback attribute totrue, meaning that when the exception handler catches an exception of the defined type, aTransferException is raised, and a rollback is signaled for the transaction.
>>> Exception class: |
Transactioncontrol attributes can be specified either as embedded annotations andattributes in EJB3 or in a deployment descriptor file, which isillustrated in Figure 10.24.A descriptor file can be either hand-coded or generated fromannotations and attributes. For each EJB listed in the example file,the implicit programming model is specified (transaction-type iscontainer)and a transaction control attribute is associated with either allmethods of a class (using an asterisk) or with a particular method ofthe class (for example,transfer).
Code View: Scroll / Show All <ejb-jar> |
Inthe Java EE environment, explicit transaction programming directly usesthe Java Transaction API (JTA) in a bean-managed transaction. JTA hasthree major functional areas:
Simple transaction demarcation: javax.transaction.UserTransaction
Transaction manger control: javax.transaction.TransactionManager
A Java mapping of the XA API for resource integration: javax.transaction.xa.XAResource
TheUserTransaction part of the API is used for bean managed transactions; that is, for explicit transaction programming in an EJB. TheTransactionManagerpart of the API typically is used by application server vendors toaccess and control the functions of an independent transaction manager,such as a Java Transaction Service (JTS) compliant transaction manager.Some application server products explicitly prohibit its use. TheXAResourceportion of the API is a Java mapping of the standard XA interface thatthe application server uses to include XA-compliant resource managersinto JTA-managed transactions.
Theunderlying implementation of JTA isn’t explicitly defined and may varyfrom vendor to vendor. JTS specifies one implementation, using theObject Management Group’s Object Transaction Service (OTS, described inSection 10.8)and General Inter-ORB Protocol (IIOP). Vendors typically use acombination of JTS and XA-compliant libraries. Transactioninteroperability between transactional Java EE application servers isoptional, but if supported it must use JTS/OTS.
JTAcan be used in a Java EE environment. It can also be used outside aJava EE environment when an independent implementation of JTA isavailable, such as Atomikos or the JBoss Transaction Manager.
Figure 10.25 illustrates the use of explicit transaction management within a stateless session bean. TheUserTransaction part of the JTA API is used in a stateless EJB to start (utx.begin()) and terminate (utx.commit())a transaction. A transaction has to be started and completed in thesame method, although the transaction context (as in the implicitmodel) can be propagated to other methods. As shown in the example, anexception handler can be defined to issue theutx.rollback()command and throw an exception to the client if there’s a problem.
@Stateless |
TheJava Connector Architecture (JCA) defines a standard way forJava-EE-compliant transactional middleware to connect to legacy TPmonitors and other existing systems such as packaged applications. JCAprovides a set of APIs and system programming interfaces for developingand deploying connections and adapters to existing systems.JCA can propagate a transaction context from an EJB to a legacy TPmonitor, depending on the compatibility of the application server’s andlegacy TP monitor’s transaction protocols.
JCAdefines a set of system-level contracts between a Java EE applicationserver and an existing system. They include contracts forcommunications, security, and transaction management. JCA defines acommon client interface that allows an EJB to call an adapter writtenfor an existing technology’s external client or a custom-developedadapter. It can propagate application server features using one or moreconnection contracts, such as one that propagates transaction context.JCA calls such a contract a resource adapter.A resource adapter plugs into the application server as a protocol andfunctional bridge between an application server and an existing system.
Transactionmanagement is integrated with JTA and is based on wrapping eachexisting transactional environment as an XA resource so it can becoordinated using the application server’s transaction manager. JCAoffers the application server the option to delegate transactionmanagement to the local resource when a single resource manager isinvolved in the transaction, saving the overhead of two-phase commitcoordination when it isn’t needed. Transaction propagation works withboth the implicit and explicit programming models.
Existingsystems such as legacy TP monitors typically support external clients,for example ECI for CICS and TP Web Connector for ACMS. Vendors alsohave the option of providing their own JCA-compliant adapter. JCAadapters are capable of bidirectional communication, includingtransactions, between existing systems and application servers.
TheSpring Framework is a popular open source programming model fordeveloping enterprise applications, such as TP applications, usingplain old Java objects (POJOs) and EJBs. Spring objects, called SpringBeans, can be deployed into Java-EE-compliant application servers,standalone servlet engines that don’t support EJBs, or OSGi Frameworkssuch as Eclipse Equinox and Apache Felix.
TheSpring Framework offers a widely-adopted lightweight alternative toEJBs, including transactional middleware functions. Spring works withpopular EJB containers and standalone JTA-compliant transactionmanagers such as the JBoss Transaction Manager, the Atomikostransaction manager, or the Java Open Transaction Manager (JOTM) fromthe OW2 Consortium. The Spring Framework extends transaction processingapplications outside of the Java-EE-compliant application serverenvironment and offers a lightweight alternative for single resourcetransactions.
Spring supports two models for transaction management:
Local: Delegates transaction management to the persistence abstraction mechanism (e.g., JDBC or JPA)
JTA: Uses the JTA API from within the Spring Platform Transaction Manager API explicitly to initiate and terminate transactions
Springsupports both implicit and explicit programming models for either thelocal or JTA transaction management models. The implicit and explicitmodels are called declarative and programmatic demarcation,respectively. Declarative demarcation uses embedded annotations whereasprogrammatic demarcation uses the JTA API. Spring Beans usingtransactions can be deployed within an EJB container or independentlyof an EJB container as long as the requisite transaction managementinfrastructure is available (i.e., a transactional persistenceabstraction mechanism and/or a standalone JTA implementation).
Springtransaction management uses the Spring Platform Transaction Manager APIto abstract the transaction management and programming models. Thelocal and JTA transaction management models are strategies.A transaction management strategy is defined or altered using aconfiguration file associated with a Spring Bean. The Spring Frameworkfocuses primarily on local transaction management as the most commonuse of two-phase commit; that is, coordinating transactional resourcesthat reside on the same machine.
TheSpring Framework supports local propagation of transaction contextacross method invocations using either strategy. Remote propagation oftransaction context uses a JTA-aware communication protocol (e.g., RMIand RMI/IIOP) and requires explicit JTA programming.
TheSpring Framework allows TP application developers to define whichexceptions will cause a rollback, a capability that is also availablein EJB3.
As shown in Figure 10.26, the Spring Framework uses thePlatformTransactionManagerinterface to implement the transaction strategy declared for a SpringBean. The strategy can choose a transaction manager that provides a JTAAPI, or it can use the transaction management capabilities of a JDBCconnection. However, it is also possible for a Java programmer to usethis interface directly from a Spring Bean to programmatically set thestrategy.
public interface PlatformTransactionManager { |
In Figure 10.27 thePROPAGATION_REQUIREDattribute is set to ensure that the method is invoked within atransaction context. Note that remote context propagation requires theuse of the explicit programming model. The example also illustrates theway in which the Spring Framework allows a rollback to be associatedwith an application defined exception, such asMyException.
DefaultTransactionDefinition def = new DefaultTransactionDefinition(); |
The implicit model implements declarative demarcation using Spring’s@Transactional annotation. This works similarly to EJB’s annotation system. Spring supports the EJB@TransactionAttribute values and extends them for defining a custom isolation level or a read-only transaction, or to control cache flushing.
In the example in Figure 10.28, the@Transactional annotation indicates using thePropagation.REQUIRES_NEW property that a new transaction must be started before executing thewithdrawFundsmethod, even when a transaction context is propagated on the methodinvocation. Spring supports EJB propagation options and adds aNESTEDoption to support nested transactions. This can be used by persistenceabstraction mechanisms that support savepoints, such as a JDBC3 driveror Apache OpenJPA.
@Transactional(propagation=Propagation.REQUIRES_NEW) |
Switchingthe transaction management strategy from local to JTA is accomplishedusing a configuration change. For example, the first part of Figure 10.29configures the local Spring transaction management strategy to use aJDBC driver and the second part configures a JTA strategy. Aconfiguration change to a JTA strategy may be necessary when a SpringBean accesses multiple resource managers within the same transaction,or needs to propagate transaction context remotely.
<tx:annotation-driven/>
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="myTargetDataSourceBean"/>
</bean>
<tx:annotation-driven/>
<bean id="transactionManager"
class="org.springframework.transaction.jta.JtaTransactionManager"/>