簡體   English   中英

Spring Boot在配置類中注入EntityManagerFactory

[英]Spring boot inject EntityManagerFactory in configuration class

我正在使用Spring Boot,並且我想將Spring與Hibernate集成在一起。 我想制作一個Session Factory bean以便進一步使用。 但是我不能自動裝配EntityManagerFactory,我不能僅在配置類中自動裝配它,在其他類中也可以工作。 你能幫忙嗎?

配置類

package kz.training.springrest.configuration;

@Configuration
@EnableTransactionManagement
public class DatabaseConfiguration {

    @Autowired
    private EntityManagerFactory entityManagerFactory;

    @Bean
    public SessionFactory getSessionFactory() {
        if (entityManagerFactory.unwrap(SessionFactory.class) == null) {
            throw new NullPointerException("factory is not a hibernate factory");
        }
        return entityManagerFactory.unwrap(SessionFactory.class);
    }
}

依存關系

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <version>42.2.2</version>
        </dependency
    </dependencies>

當你說

但是我不能自動連接EntityManagerFactory

是否在運行時無法編譯或引發異常? 如果是后者,那么堆棧跟蹤說明了什么?

一種可能的解決方案/解決方法是使用@PersistenceContext批注將em注入配置中,而不是em工廠:

@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();
    }
}

我不確定為什么要同時公開兩個bean,因為@chrylis指出,可以在需要的地方輕松將EMF解包為SF。

// 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();
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM