You are browsing the archive for JEE.

Using JTA inside OpenJPA in the WebSphere 7 Environment (Without EJBs)

April 10, 2012 in JEE

In some situations, you may need to manage the JTA transactions manually without using EJBs. In this post, I will show you how to do this.

Let’s see an example of a (persistence.xml) file that uses a JTA data source:

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
	<persistence-unit name="SchoolTestJPA" transaction-type="JTA">
		<provider>org.apache.openjpa.persistence.PersistenceProviderImpl</provider>	
		<jta-data-source>jdbc/school</jta-data-source>			
		<class>jpa.beans.Address</class>
		<class>jpa.beans.Person</class>
		<properties>
			<property name="openjpa.TransactionMode" value="managed"/>
    		        <property name="openjpa.ConnectionFactoryMode" value="managed"/>
		</properties>		
	</persistence-unit>
</persistence>

Thanks to the joinTransaction API of the JPA EntityManager, you can make the EntityManager able to join the current active JTA transaction. Let’s see how you can do this.

EntityManagerFactory emf = PersistentManager.getInstance().getEntityManagerFactory();
EntityManager entityManager = emf.createEntityManager();
UserTransaction userTransaction = null;

try {
        
	Context context = new InitialContext();
	userTransaction = (UserTransaction) context.lookup("java:comp/UserTransaction");
	
	userTransaction.begin();

	entityManager.joinTransaction();
        
	
        // Perform the operations here ...
	entityManager.persist(someThing);
	
	userTransaction.commit();
} catch (Exception exception) {
	exception.printStackTrace();
	
	try {
		if (userTransaction != null && userTransaction.getStatus() == Status.STATUS_ACTIVE) {
			userTransaction.rollback();
		}
	} catch (Exception rollbackException) {
		rollbackException.printStackTrace();
	}
} finally {
	if (entityManager != null) {
		entityManager.close();
	}
}

As you see here, by performing the JNDI lookup on the “java:comp/UserTransaction”, you can get the WebSphere JTA UserTransaction and use it instead of the JPA EntityTransaction.

Skip to toolbar