首页 > 解决方案 > 使用带有 @Transactional 的 spring bean 会给出 TransactionRequiredException: No EntityManager with actual transaction available for current thread

问题描述

我有 HttpServlet,它有一个使用 spring bean 的 doPost() 方法。那个春天有一个用@PersistenceContext() 定义的EntityManager。当 doPost() 方法收到请求时,我在运行时得到

javax.persistence.TransactionRequiredException:没有可用于当前线程的具有实际事务的 EntityManager - 无法可靠地处理“持久”调用

代码是这样的(请原谅编写骨架代码):

class MyServlet extends HttpServlet {

@Autowired
SpringBean springBean;

@Override
    public void init(ServletConfig config) throws javax.servlet.ServletException{
        super.init(config);
        SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
}

@Override
doPost() {
 
   springBean.foo();
}
.
.
.

}

 @Service
 class SpringBean {
 @PersistenceContext(unitName = someUnitName)
 EntityManager entityManager;
 
 public void foo(){
 entityManager.persist(someEntity);
 }
 
 }

web.xml 具有组件扫描和 ContextLoaderListener 所需的参数,以使 spring 上下文可用 servlet。(还有一个没有 EntityManager 的 bean,它工作正常)

标签: javaspringservletsjbossspring-bean

解决方案


推荐阅读