package session;

import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.ejb.TransactionManagement;
import javax.ejb.TransactionManagementType;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import domain.Customer;
import domain.Order;

@Stateless
@TransactionManagement(TransactionManagementType.CONTAINER)
public class XaJpaDemoBean {

	@PersistenceContext(name="customer") EntityManager customerEntityManager;
	@PersistenceContext(name="orders") EntityManager orderEntityManager;
	
	@TransactionAttribute(TransactionAttributeType.REQUIRED)
	public Customer findCustomer(int id) {
		return customerEntityManager.find(Customer.class, id);
	}

	@TransactionAttribute(TransactionAttributeType.REQUIRED)
	public void saveCustomerOrder(Customer c, Order o, Boolean succeeds) {
		System.out.println("XaJpaDemoBean.saveCustomerOrder()");
		try {

			// Update the customer entity in the database.
			c.setNumberOfOrders(c.getNumberOfOrders() + 1);
			System.out.println("XaJpaDemoBean.saveCustomerOrder(): Updated Customer with Id " + c.getId());

			// Insert the order entity in the database.
			orderEntityManager.persist(o);

			System.out.println("XaJpaDemoBean.saveCustomerOrder(): Created order with Id " + o.getId());

		} finally {	
			if (!succeeds) {
				throw new RuntimeException("XaJpaDemoBean.saveCustomerOrder(): Simulated failure!");
			}
		}
	}
}

@@ -11,16 +11,83 @@
 ssion;%0A%0A
+import javax.annotation.Resource;%0Aimport javax.ejb.SessionContext;%0A
 import j
@@ -106,16 +106,16 @@
 teless;%0A
-
 import j
@@ -650,16 +650,62 @@
 anager;%0A
+%09@Resource private SessionContext sessionCtx;%0A
 %09%0A%09@Tran
@@ -1450,16 +1450,16 @@
 ally %7B%09%0A
-
 %09%09%09if (!
@@ -1470,16 +1470,169 @@
 eeds) %7B%0A
+%09%09%09%09if (sessionCtx != null) %7B%0A%09%09%09%09%09sessionCtx.setRollbackOnly();%0A%09%09%09%09%7D else %7B%0A%09%09%09%09%09System.out.println(%22SessionContext is null, wrong @Resource!%22);%0A%09%09%09%09%7D%0A
 %09%09%09%09thro

Call setRollbackOnly when failure is inevitable(e.g., requested).