Spring启动会在配置类中注入EntityManagerFactory

时间:2018-06-01 12:42:31

标签: java spring hibernate spring-boot jpa

我使用弹簧靴,我想将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>

2 个答案:

答案 0 :(得分:0)

当你说

  

但我不能自动装载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();
    }
}

答案 1 :(得分:0)

我不确定你为什么要公开两个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();
  }
}