gpt4 book ai didi

java - 如何控制 EJB 容器外部的 BMT 事务?

转载 作者:行者123 更新时间:2023-12-01 12:02:24 25 4
gpt4 key购买 nike

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

为了说明这一点,我制作了这个简单的示例,在 Web 容器中启动 UserTransaction(使用 Servlet),但事务未绑定(bind)到 EJB 容器(在本例中为 BMT SFSB)。

这是为什么呢?有办法做到吗?

使用 BMT 的有状态 session 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 中启动,但 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。

关于java - 如何控制 EJB 容器外部的 BMT 事务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27900586/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com