[英]How to control a BMT transaction outside of the EJB container?
出于好奇,是否可以直接从Web容器控制EJB事务?
为了说明这一点,我做了一个简单的示例(使用Servlet)在Web容器中启动UserTransaction
,但是事务未绑定到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();
}
}
在Servlet中启动了UserTransaction,但是Session 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)
BMT在您的情况下将不起作用,因为BMT Bean将自己处理事务,并且不参与Web模块中启动的事务(容器事务)。 要使用UserTransaction控制来自servlet的事务,bean必须是CMT。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.