如何解决将Spring bean与@Transactional一起使用会产生TransactionRequiredException:没有可用于当前线程的实际事务的EntityManager
我有HttpServlet,它有一个doPost()方法,其中使用了Spring bean。那个春天有一个定义了@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,它工作正常)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。