首页 > 解决方案 > Spring Boot 2.0.x - @Configuration 类 @Autowired entityManagerFactory NullPointerException

问题描述

我使用 Hibernate 会话从 MySQL 查询数据。我使用 JPA EntityManagerFactory 来获取 Hibernate SessionFactory:

@Configuration
public class DatabaseConfig {

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

这适用于 Spring Boot 1.5.x。但是当我将 Spring Boot 更新到 2.0.1 时:

创建名称为“databaseConfig”的 bean 时出错:通过字段“entityManagerFactory”表示的依赖关系不满足;

我应该怎么做才能在 Spring Boot 2.0.x 中解决这个问题?

标签: spring-bootjpahibernate-entitymanager

解决方案


推荐阅读