java - 使用带有 @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,它工作正常)
解决方案
推荐阅读
- php - Create new array from two separate arrays by counting duplicates php
- javascript - Vue FilePond中的文件大小调整不起作用
- laravel - Ordering by foreign key field count
- machine-learning - 如果我的分类变量数量不固定,则无法为我的模型准备训练数据
- sql - T-SQL - Update list of customers CustomerID (Alphanumeric) with next in sequence
- python - 如何从停止的地方恢复 Scrapy spider?
- java - How to filter JWT authentication authorities based on http header
- javascript - 如何使用 JS 模板中的 TypeScript 添加指令?
- checkbox - How to check a checkbox without unchecking?
- python - Tensorflow Advanced Indexing: Assign a smaller tensor into a bigger one into a position based on two index tensors