首页 > 解决方案 > Hibernate 5 integration with Spring Boot 2

问题描述

Am planning to create a spring boot (version 2) app with hibernate 5.3 , but am facing issues while integrating hibernate 5 . Since its a spring boot app, the container will auto configure the datasource and JPA variant EntityManagerFactory and we can create Hibernate SessionFactory from this EntityManagerFactory using the unwrap() method.

So this is my code for the Hibernate config class

@Configuration

public class HibernateUtil {

    @Autowired
    private EntityManagerFactory entityMangerFact;

    @Bean
    public SessionFactory sessionFactory() {
        return entityMangerFact.unwrap(SessionFactory.class);
    }

}

But it is thowing BeanCurrentlyInCreationException . But if i put the unwrap() in the service class method , it wont throw exceptions .but i think that not the right thing, since we will have more service methods, and we may need to call unwrap() on each service methods. Error log:

Caused by: org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'sessionFactory': Requested bean is currently in creation: Is there an unresolvable circular reference?
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.beforeSingletonCreation(DefaultSingletonBeanRegistry.java:339) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:215) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]

Why the unwrap() is failing in the configuration class ?

标签: javaspringhibernatespring-boot

解决方案


在 spring-boot 中,您可以访问 EntityManagerFactory ,因为您可以签入此数据源配置,但您不需要EntityManager直接使用与数据库交互,您可以使用spring-data-jpa


推荐阅读