No transactional entitymanager available in @PostConstruct

后端 未结 1 996
后悔当初
后悔当初 2021-01-24 08:22

Problem: entityManager.unwrap(SessionImplementor.class) cause no transactional entitymanager available exception.

Code

1条回答
  •  礼貌的吻别
    2021-01-24 09:14

    According to this excelent answer:

    In the @PostConstruct (as with the afterPropertiesSet from the InitializingBean interface) there is no way to ensure that all the post processing is already done, so (indeed) there can be no Transactions.

    As I see, you do not need a transaction nor an entity manager bean, but rather an entity manager factory bean. I think you should simply autowire the EntityManagerFactory and then unwrap the Hibernate SessionFactory from it.

    @Autowired
    private EntityManagerFactory entityManagerFactory;
    
    @PostConstruct
    public void registerListeners() {
        SessionFactory sessionFactory = entityManagerFactory.unwrap(SessionFactory.class);
        ...
    }
    

    0 讨论(0)
提交回复
热议问题