我试图用下面的行从JPA的SessionFactory创建Hibernate的EntityManager bean,但是EntityManger是空的,我不想在configuration类中扩展为SessionFactory创建bean的JPARepository.Hences。
@Configuration
public class 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>application.properties
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=test
spring.datasource.password=test
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect发布于 2021-09-18 13:10:55
我相信您需要使用@EnableJpaRepositories自动装配EntityManager是由Spring模块提供的一个特性。它不是由Spring集成提供的。
也可以使用@PersistenceContext不使用Spring注入EntityManager。这如Spring参考文档https://docs.spring.io/spring-framework/docs/current/reference/html/data-access.html#dao-annotations所示
发布于 2021-09-19 06:57:29
我的问题得到了解决:
调试内部Springboot代码后,可以在存储库类中获取entityManager实例。
EntityManager实例在configuration中为null,而在Repository类中EntityManager不是null。
https://stackoverflow.com/questions/69233275
复制相似问题