Spring boot inject EntityManagerFactory in configuration class

后端 未结 2 1978
失恋的感觉
失恋的感觉 2021-01-27 03:02

I\'m using spring boot and i want to integrate spring with hibernate. I want to make a Session Factory bean for further using. But I can\'t autowire EntityManagerFactory, I can\

2条回答
  •  猫巷女王i
    2021-01-27 03:24

    When you say

    But I can't autowire EntityManagerFactory

    does it fail to compile or throw an exception at run-time? If the latter, what does the stack-trace say?

    One possible solution/work around might be to inject an em into the configuration instead of the em factory, using the @PersistenceContext annotation:

    @Configuration
    @EnableTransactionManagement
    public class DatabaseConfiguration {
    
        @PersistenceContext
        private EntityManager entityManager;
    
        @Bean
        public SessionFactory getSessionFactory() {
            // no need to check for null here because if the unwrap fails, it will do
            // so by throwing a PersistenceException rather than returning null.
            return entityManager.unwrap( Session.class ).getFactory();
        }
    }
    

提交回复
热议问题