如何在EJB容器外控制BMT事务?

时间:2015-01-12 11:06:58

标签: java java-ee transactions

出于好奇,是否可以直接从Web容器控制EJB事务?

为了说明我做了这个简单的例子,在Web容器中启动UserTransaction(使用Servlet),但事务没有绑定到EJB容器(在本例中是BMT SFSB)。

为什么?有办法吗?

使用BMT的有状态会话Bean

@Stateful
@TransactionManagement(TransactionManagementType.BEAN)
public class CustomerBean implements CustomerBeanLocal{

    @PersistenceContext(type=PersistenceContextType.EXTENDED)
    private EntityManager em;

    @Override
    public Integer createCustomer(String name) {

        Customer customer = new Customer();
        customer.setId(1);
        customer.setName(name);
        em.persist(customer);
        //em.flush();

        return customer.getId();
    }   
}

UserTransaction在Servlet中启动,但会话Bean不会持续

客户不会持久保存到数据库中。

public class BMTServlet extends HttpServlet {

    @EJB
    private CustomerBeanLocal customerBean;

    @Resource
    private UserTransaction userTransaction;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        try {           

            userTransaction.begin();

            customerBean.createCustomer("Tars");       

            userTransaction.commit();

        } catch (Exception e) {
            throw new ServletException(e);
        }
    }
}

如果我们取消注释em.flush();,那么我们会得到以下异常:

javax.persistence.TransactionRequiredException: no transaction is in progress
    org.hibernate.ejb.AbstractEntityManagerImpl.flush(AbstractEntityManagerImpl.java:792)
    org.jboss.ejb3.jpa.integration.JPA1EntityManagerDelegator.flush(JPA1EntityManagerDelegator.java:86)
    bean.CustomerBean.createCustomer(CustomerBean.java:25)

1 个答案:

答案 0 :(得分:1)

BMT将无法在您的方案中运行,因为BMT bean将自行处理事务,并且不会参与在Web模块中启动的事务(容器事务)。要使用UserTransaction从servlet控制事务,bean必须是CMT。