【问题标题】:EntityManager is null evenAfter added the springDataJpa dependencyEntityManager 为 null 甚至添加了 springDataJpa 依赖后
【发布时间】:2021-11-12 21:55:10
【问题描述】:

我正在尝试使用以下几行从 JPA 的 EntityManager 创建 Hibernate 的 SessionFactory bean 但我得到的 EntityManger 为空。我不想扩展 JPARepository。因此在配置类中为 SessionFactory 创建 bean。

@配置
公共类 BeanConfig {

@Autowired
EntityManager entityManager;

@Bean
public SessionFactory getSessionFactory() {

    if (entityManager == null) {
        logger.info("EntityManager is null---");
    } else {
        if (entityManager.unwrap(Session.class) == null) {

            return entityManager.unwrap(Session.class).getSessionFactory();
        }
    }
    return null;
}

}

控制台中打印的记录器信息: EntityManager 为空---

pom.xml

<dependencies>
     <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency> 
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
     
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    
     <dependency>
            <groupId>mysql</groupId>
             <artifactId>mysql-connector-java</artifactId>        
        </dependency>
</dependencies><br>

application.properties
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=更新
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=test
spring.datasource.password=测试
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect

【问题讨论】:

    标签: java configuration null javabeans entitymanager


    【解决方案1】:

    我相信你需要使用@EnableJpaRepositories EntityManager 的自动装配是 Spring Data JPA 模块提供的一项功能。通常的 Spring JPA 集成不提供它。

    或者您可以使用@PersistenceContext 注入EntityManager 而不使用Spring Data JPA。这显示在 Spring Framework 参考文档https://docs.spring.io/spring-framework/docs/current/reference/html/data-access.html#dao-annotations

    【讨论】:

      【解决方案2】:

      为我的问题找到了解决方案:
      调试内部 Springboot 代码后,我能够在存储库类中获取 entityManager 实例。

      EntityManager 实例在配置类中为空,但 EntityManager 在 Repository 类中不为空。

      【讨论】:

        猜你喜欢
        • 2021-02-27
        • 2016-08-20
        • 1970-01-01
        • 2019-08-18
        • 1970-01-01
        • 2018-08-18
        • 1970-01-01
        • 2017-01-05
        • 1970-01-01
        相关资源
        最近更新 更多