简体   繁体   中英

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 ?

在spring-boot中,您可以访问EntityManagerFactory,因为您可以检查此数据源配置,但无需直接使用EntityManager与数据库进行交互,可以使用spring-data-jpa

Can you try injecting it as SessionFactory bean dependency and not @Configuration bean?

@Configuration
public class HibernateUtil {

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM