@PostConstruct和“没有休眠会话绑定到线程";例外 [英] @PostConstruct and "No Hibernate Session bound to thread" exception
问题描述
我必须在存储库的@PostConstruct
中做一些数据库工作:
I have to do some database stuff in my repository' @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
有什么简单的解决方案吗?
is there any easy solution for that?
谢谢!
推荐答案
假定您将结合使用spring的hibernate和已在spring config文件中正确配置了sessionFactory和事务管理器. 然后,根本原因是当调用doSomestuffWithDb()方法时,事务准备工作到Spring尚未完成. @postconstruct只能确保在创建bean之后调用该方法,它不能确保容器当前已准备好一切(这里是指与事务相关的东西). 春季论坛上有详细的讨论. http://forum.springsource .org/showthread.php?58337-No-transaction-in-transactional服务称为-from-PostConstruct 此外,作者在以下位置向吉拉提交了解决方案: https ://jira.springsource.org/browse/SPR-5966?page = com.atlassian.jira.plugin.system.issuetabpanels:all-tabpanel#issue-tabs
assuming you are using hibernate combining with spring and you have configured your sessionFactory and transaction manager correctly in your spring config file. Then the root cause is that when your doSomestuffWithDb() method is invoked the transaction prepare work has not been finished by spring. The @postconstruct can only ensure the method is called after the bean is created, it can not ensure the container is ready for everything- here, I mean the transaction related stuff- at the moment. There is a detailed discussion in spring forum. http://forum.springsource.org/showthread.php?58337-No-transaction-in-transactional-service-called-from-PostConstruct Also, the author submitted his solution to jira at https://jira.springsource.org/browse/SPR-5966?page=com.atlassian.jira.plugin.system.issuetabpanels:all-tabpanel#issue-tabs
这篇关于@PostConstruct和“没有休眠会话绑定到线程";例外的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!