简体   繁体   English

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

[英]How to control a BMT transaction outside of the EJB container?

Just out of curiosity, is it possible to directly control an EJB transaction from the Web Container? 出于好奇,是否可以直接从Web容器控制EJB事务?

To illustrate I made this simple example initiating a UserTransaction in the Web Container(using a Servlet), but the transaction is not bound to the EJB Container (in this case a BMT SFSB). 为了说明这一点,我做了一个简单的示例(使用Servlet)在Web容器中启动UserTransaction ,但是事务未绑定到EJB容器(在本例中为BMT SFSB)。

Why is it? 为什么? Is there a way to do it? 有办法吗?

Stateful Session Bean using BMT 使用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 is initiated in the Servlet, but the Session Bean doesn't persist 在Servlet中启动了UserTransaction,但是Session Bean不持久

The Customer is not persisted to the database. 客户未持久到数据库。

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);
        }
    }
}

If we uncomment the em.flush(); 如果我们取消注释em.flush(); then we get the following exception: 那么我们得到以下异常:

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)

BMT will not work in your scenario, as BMT bean will be handling transaction by itself and will not participate in the transaction started in the web module (the container transaction). BMT在您的情况下将不起作用,因为BMT Bean将自己处理事务,并且不参与Web模块中启动的事务(容器事务)。 To control transaction from servlet using UserTransaction, the bean must be CMT. 要使用UserTransaction控制来自servlet的事务,bean必须是CMT。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM