我正在使用 Spring Boot,我想将 Spring 与 Hibernate 集成。我想制作一个会话工厂 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
它是否无法编译或在运行时抛出异常?如果是后者,堆栈跟踪会说什么?
一种可能的解决方案/解决方法可能是使用 em 注入配置而不是 em 工厂@PersistenceContext
注解:
@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();
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)