简体   繁体   中英

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?

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).

Why is it? Is there a way to do it?

Stateful Session Bean using BMT

@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

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(); 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). To control transaction from servlet using UserTransaction, the bean must be CMT.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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