In this tutorial we shall show you how to implement JTA multiple resource transactions in a?Tomcat?server, using?Atomikos Transaction Manager. Atomicos transaction manager provides support for distributed transactions. These are multi-phased transactions, often using multiple databases, that must be committed in a coordinated way. The distributed transactions are described by the?XA standard.?XA?governs how a transaction manager (such as Atomikos) can tell a database what work is going on as part of what transaction, and how to conduct the two-phase commit (2PC) protocol at the end of each transaction.
Here, we will create simple Entity classes mapped to two different databases and we will try to persist objects of the classes to the databases using one distributed transaction. We will also see what happens when one of the underlying transactions rollbacks.
Our preferred development environment is?Eclipse. We are using Eclipse Juno (4.2) version, along with?Maven?Integration plugin version 3.1.0. You can download Eclipse from?here?and Maven Plugin for Eclipse from?here. The installation of Maven plugin for Eclipse is out of the scope of this tutorial and will not be discussed. We are also using Spring version 3.2.3 and the JDK 7_u_21.
Tomcat 7?is the application server used. Hibernate version is 4.1.9, and the database used in the example is MySQL Database Server 5.6.
Let’s begin,
1. Create a new Maven project
Go to File -> Project ->Maven -> Maven Project.
In the “Select project name and location” page of the wizard, make sure that “Create a simple project (skip archetype selection)” option is?unchecked, hit “Next” to continue with default values.
Here the maven archetype for creating a web application must be added. Click on?“Add Archetype”?and add the archetype. Set the “Archetype Group Id” variable to?"org.apache.maven.archetypes", the “Archetype artifact Id” variable to?"maven-archetype-webapp"?and the “Archetype Version” to?"1.0". Click on?“OK”?to continue.
In the “Enter an artifact id” page of the wizard, you can define the name and main package of your project. Set the “Group Id” variable to?"com.javacodegeeks.snippets.enterprise"?and the “Artifact Id” variable to?"springexample". The aforementioned selections compose the main project package as?"com.javacodegeeks.snippets.enterprise.springexample"?and the project name as?"springexample". Set the “Package” variable to?"war", so that a war file will be created to be deployed to tomcat server. Hit “Finish” to exit the wizard and to create your project.
The Maven project structure is shown below:
It consists of the following folders:
?
/src/main/java folder, that contains source files for the dynamic content of the application,
/src/test/java folder contains all source files for unit tests,
/target folder contains the compiled and packaged deliverables,
/src/main/resources/webapp/WEB-INF folder contains the deployment descriptors for the Web application ,
the pom.xml is the project object model (POM) file. The single file that contains all project related configuration.
2. Add Spring 3.2.3 dependency
Locate the “Properties” section at the “Overview” page of the POM editor and perform the following changes: Create a new property with name?org.springframework.version?and value?3.2.3.RELEASE.
Navigate to the “Dependencies” page of the POM editor and create the following dependencies (you should fill the “GroupId”, “Artifact Id” and “Version” fields of the “Dependency Details” section at that page): Group Id :?org.springframework?Artifact Id :?spring-web?Version :?${org.springframework.version}
Alternatively, you can add the Spring dependencies in Maven’s?pom.xml?file, by directly editing it at the “Pom.xml” page of the POM editor, as shown below: ? pom.xml:
As you can see Maven manages library dependencies declaratively. A local repository is created (by default under {user_home}/.m2 folder) and all required libraries are downloaded and placed there from public repositories. Furthermore intra – library dependencies are automatically resolved and manipulated.
3. Add all required dependencies
All dependencies needed to set up atomicos transaction manager are set here. pom.xml
EmployeeA.java?and?EmployeeB.java?are the Entity classes. They use the?javax.persistence?annotations to be mapped to a table,?EMPLOYEEA?and?EMPLOYEEB?in different databases. In particular, the?@Entity?annotation specifies that each class is an entity. The?@Table?annotation specifies the primary table for the annotated entity. The?@Column?annotation is used to specify a mapped column for the persistent field, whereas the?@Id?annotation specifies the primary key field of each entity.
The Data Access Obejcts implemented are the?EmployeeADAOImpl.java?and?EmployeeBDAOImpl.java?classes. They are annotated with the?@Service?annotation, dictating that they are Spring Beans and thus allowing Spring to auto-detect them. They both use thejavax.persistence.EntityManager?to interact with the databases.
An?EntityManager?instance is associated with a persistence context. A persistence context is a set of entity instances in which for any persistent entity identity there is a unique entity instance. Within the persistence context, the entity instances and their lifecycle are managed. The?EntityManager?API is used to create and remove persistent entity instances, to find entities by their primary key, and to query over entities. The?EntityManager?is configured in?persistence.xml?file, that is described in paragraph 8.1. The set of entities that can be managed by a given EntityManager instance is defined by a persistence unit. A persistence unit defines the set of all classes that are related or grouped by the application, and which must be colocated in their mapping to a single database.
The?EntityManager?is injected in each DAO with the?@PersistenceContext?annotation, where the name of each persistence unit is set, as defined in the?persistence.xml?file. A basic persist method is implemented in both DAOs, using the?persist(Object entity)?API method of?EntityManager?to create an object to the database.
The?EmployeeADAOImpl.java?and?EmployeeBDAOImpl.java?classes are injected in the?EmployeeServiceImpl.java?class. Thus, in thepersistEmployees(EmployeeA employeeA, EmployeeB employeeB)?method implemented here, the DAOs’ methods are invoked to perform the basic interaction with the database. The?EmployeeServiceImpl.java?class is also annotated with the?@Serviceannotation, dictating that it is a Spring Bean and thus allowing Spring to auto-detect it.
The?@Transactional?annotation is placed before the method, to denote that a transaction is created when the method is invoked. The transaction is a global container managed transaction and will be configured in Spring configuration file. EmployeeService.java
????????System.out.println("Persist A OK - persist B");
26
????????employeeBDAO.persistEmployee(employeeB);
27
????????System.out.println("Persist B okk");
28
????}
29
?
30
}
7. Create a servlet to run the application
The?AppServlet.java?class is a simple servlet, that implements the?org.springframework.web.HttpRequestHandler?and overrides itshandleRequest(HttpServletRequest req, HttpServletResponse resp)?API method. The?EmployeeService?is injected here, via the@Autowire?annotation. It is used in the?handleRequest(HttpServletRequest req, HttpServletResponse resp)?API method to persist a new?EmployeeA?and a new?EmployeeB?object. The method also returns a success message if the method returns succesfully and rollback message if the method throws an exception.
As mentioned above, the?entityManager?and the persistence unit associated with it for every database is configured inpersistence.xml?file. Here we define two persistence units. In every?persistence-unit?element, we define the entity class associated to the persistence-unit. The?hibernate.transaction.manager_lookup_class?property is set tocom.atomikos.icatch.jta.hibernate3.TransactionManagerLookup. The?hibernate.transaction.factory_class?property is set toorg.hibernate.transaction.CMTTransactionFactory. persistence.xml
The?applicationContext.xml?file is the configuration file of Spring.
The?<context:component-scan/>?element is used to set the package that contains all classes that the container must scan to detect the Spring beans. The?<tx:annotation-driven/>?element is also used so that Spring is @Transactional-aware and can detect the?@Transactionalannotations to configure the appropriate beans with transactional behavior. The?<jta-transaction-manager/>?element is used to detect the underlying server and choose the transaction manager available for the platform.
In?dataSourceA?and?dataSourceB?beans we define the datasources. The?com.atomikos.jdbc.AtomikosDataSourceBean?is the class set here. It uses Atomikos JTA-enabled connection pooling. It has two properties to configure. Thecom.mysql.jdbc.jdbc2.optional.MysqlXADataSource?class is set to the?xaDataSourceClass?property, whereas in thexaProperties?we can set the properties (name,value pairs) to configure the?XADataSource.
In?entityManagerFactoryA?and?entityManagerFactoryB?beans we set theorg.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean?class. It is a?FactoryBean?that creates a JPAEntityManagerFactory?according to JPA’s standard container bootstrap contract. We can set the?persistence.xml?location in itspersistenceXmlLocation?property. We can set the name of the persistence unit used to create this?EntityManagerFactory, inpersistenceUnitName?property. The?datasource?property is reference to the appropriate?dataSource?bean. ThejpaVendorAdapter?property is set to the?org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter, that is an implementation for Hibernate?EntityManager.
Finally, the?transactionManager?bean is defined, using the?org.springframework.transaction.jta.JtaTransactionManager. It holds two properties to configure. The?transactionManager, and the?atomikosTransactionManager. They are references to two beans of?com.atomikos.icatch.jta.UserTransactionManager?class and?com.atomikos.icatch.jta.J2eeUserTransactionclass respectively. applicationContext.xml
8.3 Configure Web Application Deployment Descriptor
The?web.xml?file is the file that defines everything about your application that a server needs to know. Servlets and other components like filters or listeners, initialization parameters, container-managed security constraints, resources, welcome pages, etc are set here.
The?servlet?element declares the?AppServlet, and the?org.springframework.web.context.support.HttpRequestHandlerServletclass that implements it. The?servlet-mapping?element specifies the?/appServlet?URL pattern that invokes the servlet in a browser. In the?context-param?element we set the?contextConfigLocation?parameter, where the?applicationContext.xml?file location is defined. In?listener?element the Bootstrap listener is set to start up Spring’s?applicationContext.xml. The?resource-ref?element is set in both datasources to define a reference lookup name to the resources. This allows the servlet code to look up the resources by a “virtual” name that is mapped to the actual location at deployment time.
In order to run the application in tomcat we first have to build the project. The?war?produced is placed at webapps folder of tomcat. Then, we startup the server. After hitting on
localhost:8080/springexample/appServlet
in a browser, we can check on MySQL, that in both databases,?companyA?and?companyB?the tables?EmployeeA?and?EmployeeB?have one record. The message returned in the browser is the one below:
10. Rollback case
Now, let’s see what happens if one of the two transactions fail. We will change the?persistEmployee(EmployeeB employee)?method ofEmployeeBDAOImpl.java?class so as to throw an?Exception.
We build the project again and place the new?war?file in webapps file of tomcat. After starting up tomcat again, the result is the one below:
This is caused because since one of the transactions throws an exception the distributed transaction rolls back too. ? This was an example of JTA multiple resource transactions in a Tomcat server, using Atomikos Transaction Manager. Download the Eclipse project of this tutorial :?SpringJTAatomicosTomcatExample.zip