Chapter 7.  Persistence Units and Persistence Contexts

Identify correct and incorrect statements or examples about JTA and resource-local entity managers.

[Note]

Depending on the transactional type of the entity manager, transactions involving EntityManager operations may be controlled either through JTA or through use of the resource-local EntityTransaction API, which is mapped to a resource transaction over the resource that underlies the entities managed by the entity manager.

An entity manager whose underlying transactions are controlled through JTA is termed a JTA entity manager.

An entity manager whose underlying transactions are controlled by the application through the EntityTransaction API is termed a resource-local entity manager.

A container-managed entity manager MUST be a JTA entity manager. JTA entity managers are only specified for use in Java EE containers.

An application-managed entity manager may be either a JTA entity manager OR a resource-local entity manager.

An entity manager is defined to be of a given transactional type - either JTA or resource-local - at the time its underlying entity manager factory is configured and created.

Both JTA entity managers and resource-local entity managers are required to be supported in Java EE web containers and EJB containers. Within an EJB environment, a JTA entity manager is typically used. In general, in Java SE environments only resource-local entity managers are supported.

JTA EntityManagers

An entity manager whose transactions are controlled through JTA is a JTA entity manager. A JTA entity manager participates in the current JTA transaction, which is begun and committed external to the entity manager and propagated to the underlying resource manager.

An example persistence.xml file (Java EE) is shown below:


<persistence 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"
	version="1.0">
	
	<persistence-unit name="ShopPU" transaction-type="JTA">
		...
	</persistence-unit>
	
</persistence>

					

NOTE: by default transaction type is JTA.

Resource-local EntityManagers

An entity manager whose transactions are controlled by the application through the EntityTransaction API is a resource-local entity manager. A resource-local entity manager transaction is mapped to a resource transaction over the resource by the persistence provider. Resource-local entity managers may use server or local resources to connect to the database and are unaware of the presence of JTA transactions that may OR may not be active.

An example persistence.xml file (Java SE) is shown below:


<persistence 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"
	version="1.0">
	
	<persistence-unit name="ShopPU" transaction-type="RESOURCE_LOCAL">
		...
	</persistence-unit>
</persistence>

					

The EntityTransaction Interface

The EntityTransaction interface is used to control resource transactions on resource-local entity managers. The EntityManager.getTransaction() method returns the EntityTransaction interface.

When a resource-local entity manager is used, and the persistence provider runtime throws an exception defined to cause transaction rollback, it MUST mark the transaction for rollback.

If the EntityTransaction.commit() operation fails, the persistence provider MUST roll back the transaction.

public interface EntityTransaction {

	public void begin();

	public void commit();

	public void rollback();

	public void setRollbackOnly();

	public boolean getRollbackOnly();

	public boolean isActive();
}
					

The begin, commit, and rollback methods demarcate transaction boundaries. The methods should be self-explanatory: begin starts a transaction, commit attempts to commit the transaction's changes to the datastore, and rollback aborts the transaction, in which case the datastore is "rolled back" to its previous state. JPA implementations will automatically roll back transactions if any exception is thrown during the commit process.

Unless you are using an extended persistence context, committing or rolling back also ends the persistence context. All managed entites will be detached from the EntityManager.

The isActive() method returns true if the transaction is in progress (begin has been called more recently than commit or rollback), and false otherwise.

The following example illustrates the creation of an entity manager factory in a Java SE environment, and its use in creating and using a resource-local entity manager:

public class PasswordChanger {

	public static void main (String[] args) {
		EntityManagerFactory emf = Persistence.createEntityManagerFactory("Order");
		EntityManager em = emf.createEntityManager();

		em.getTransaction().begin();

		User user = (User)em.createQuery("SELECT u FROM User u WHERE u.name=:name AND u.pass=:pass")
			.setParameter("name", args[0])
			.setParameter("pass", args[1])
			.getSingleResult();

		if (user!=null) {
			user.setPassword(args[2]);
		}	

		em.getTransaction().commit();

		em.close();
		emf.close ();
	}
}
					

Example. Grouping Operations with Transactions:

public void transferFunds(EntityManager em, User from, User to, double amnt) {
	EntityTransaction trans = em.getTransaction();
	trans.begin();
	try {
		from.decrementAccount(amnt);
		to.incrementAccount(amnt);
		trans.commit();
	} catch (RuntimeException re) {
		if (trans.isActive()) {
			trans.rollback();   // or could attempt to fix error and retry
		}    
		throw re;
	}
}
					

Professional hosting     Belorussian informational portal         Free SCWCD 1.4 Study Guide     Free SCDJWS 1.4 Study Guide     SCDJWS 1.4 Quiz     Free IBM Certified Associate Developer Study Guide     IBM Test 000-287. Enterprise Application Development with IBM WebSphere Studio, V5.0 Study Guide     Free Mock Exam Engine