繁体   English   中英

@PostConstruct和“没有Hibernate Session绑定到线程”异常

[英]@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无法启动事务
  • hibernate需要一个事务来改变数据(插入/更新/删除)

因此,您必须从会话工厂(通过.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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM