简体   繁体   中英

@PostConstruct and “No Hibernate Session bound to thread” exception

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() {
        ...
    }

}

but it fails with:

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?

Thanks!

  • You don't have a running transaction in @PostConstruct
  • you can't use @Transactional there (except for mode="aspectj" ), so spring can't start the transaction
  • a transaction is required for hibernate to mutate data (insert/update/delete)

So, you would have to create your session from the session factory (via .openSession() ) there and start a transaction manually.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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