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

时间:2011-04-12 12:19:26

标签: java hibernate spring

我必须在我的资源库@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

有什么简单的解决方案吗?

谢谢!

2 个答案:

答案 0 :(得分:2)

  • @PostConstruct
  • 中没有正在运行的交易
  • 你不能在那里使用@Transactionalmode="aspectj"除外),所以spring无法启动交易
  • hibernate需要一个事务来改变数据(插入/更新/删除)

因此,您必须从会话工厂(通过.openSession())创建会话并手动启动交易。

答案 1 :(得分:2)

假设你正在使用hibernate与spring结合,并且你已经在spring配置文件中正确配置了sessionFactory和事务管理器。 然后根本原因是当调用doSomestuffWithDb()方法时,事务准备工作尚未完成。 @postconstruct只能确保在创建bean之后调用该方法,它无法确保容器已准备好用于所有内容 - 此处,我的意思是与事务相关的东西 - 此刻。 春季论坛有详细的讨论。 http://forum.springsource.org/showthread.php?58337-No-transaction-in-transactional-service-called-from-PostConstruct 此外,作者向jira提交了他的解决方案 https://jira.springsource.org/browse/SPR-5966?page=com.atlassian.jira.plugin.system.issuetabpanels:all-tabpanel#issue-tabs

相关问题