我必须在我的存储库中做一些数据库工作' @PostConstruct
:
@Repository
public class SomeRepositoryHibernate implements SomeRepository {
private SessionFactory sessionFactory;
@Autowired
public SomeRepositoryHibernate(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
...
@PostConstruct
public void doSomestuffWithDb() {
...
}
}
但它失败了:
org.hibernate.HibernateException: No Hibernate Session bound to thread, and
configuration does not allow creation of non-transactional one here
有什么简单的解决方案吗?
谢谢!
最佳答案
- 您在
@PostConstruct
中没有正在运行的事务 - 你不能在那里使用
@Transactional
(除了mode="aspectj"
),所以spring不能启动事务 - hibernate 需要一个事务来改变数据(插入/更新/删除)
因此,您必须从那里的 session 工厂(通过 .openSession()
)创建 session 并手动启动事务。
关于java - @PostConstruct 和 "No Hibernate Session bound to thread"异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5635047/