![](/img/trans.png)
[英]Hibernate cannot find session bound to thread when using @PostConstruct
[英]@PostConstruct and “No Hibernate Session bound to thread” exception
我必須在我的存儲庫' @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無法啟動事務 因此,您必須從會話工廠(通過.openSession()
)創建會話並手動啟動事務。
假設您正在使用與spring結合的hibernate,並且已在spring配置文件中正確配置了sessionFactory和事務管理器。 然后根本原因是當調用doSomestuffWithDb()方法時,事務准備工作尚未完成。 @postconstruct只能確保在創建bean之后調用該方法,它無法確保容器已准備好用於所有內容 - 此處,我的意思是與事務相關的東西 - 此刻。 春季論壇有詳細的討論。 http://forum.springsource.org/showthread.php?58337-No-transaction-in-transactional-service-called-from-PostConstruct此外,作者還在https://jira.springsource.org上向jira提交了他的解決方案。 /browse/SPR-5966?page=com.atlassian.jira.plugin.system.issuetabpanels:all-tabpanel#issue-tabs
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.