Spring boot inject EntityManagerFactory in configuration class

后端 未结 2 1973
失恋的感觉
失恋的感觉 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条回答
  •  北海茫月
    2021-01-27 03:12

    I'm not exactly sure why you want to expose both beans because as @chrylis points out, you can easily unwrap the EMF into a SF where needed.

    // Some spring component
    @Component
    public class MyFancyComponent {
      @PersistenceContext
      private EntityManager entityManager;
    
      public void doSomethingFancy() {
        // public SessionFactory API
        final SessionFactory sf = entityManager
             .unwrap( Session.class ).getFactory();
    
        // public SessionFactoryImplementor SPI
        final SessionFactoryImplementor sfi = entityManager
             .unwrap( SessionImplementor.class ).getFactory();
      }
    }
    

提交回复
热议问题