【发布时间】:2019-06-23 09:59:49
【问题描述】:
当我在使用@Repository spring 注释注释的 Dao 实现中自动连接休眠会话工厂时,它无法创建 SessionFactory 和 Dao bean,但是它在没有 @Repository 注释的情况下工作。
我搜索了很多问题和答案,但都与早期版本的 hibernate 和 spring boot 相关,例如 unwrap 和创建会话工厂 bean,但所有这些方法都与 spring-boot 2.1 和最新的 Hibernate 版本不兼容。
在 Spring Boot 2.1 和最新的休眠版本 (5.3) 中是否有任何特定的方法来创建和自动装配休眠会话工厂?
@Repository
public class UserDaoImpl implements UserDao {
@Autowired
private SessionFactory sf;
@Override
public void addUser(User user) {
Session session = sf.getCurrentSession();
session.save(user);
}
}
在上面的代码中,SessionFactory 在没有@Repository 的情况下自动连接,我用下面的 bean 创建了一个配置类
@Configuration
public class DataConfig {
@Bean
public SessionFactory sessionFactory(@Autowired EntityManagerFactory factory) {
if (factory.unwrap(SessionFactory.class) == null) {
throw new NullPointerException("factory is not a hibernate factory");
}
return factory.unwrap(SessionFactory.class);
}
}
它当然“应用上下文中某些bean的依赖形成了一个循环:”错误
【问题讨论】:
-
为什么要用
SessionFactory,我建议改成EntityManager,用persist instead. The error is coming from the fact that as of Hibernate 5.2 theSessionFactory`扩展EntityManagerFactory。这将禁用EntityManagerFactory的 Spring 引导自动配置,现在您拥有从SessionFactory到SessionFactory的依赖关系,因为这也是EntityManagerFactory。 -
你也可以从
EntityManager解开SessionFactory
标签: java spring spring-boot