0

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 ?

Ansar Samad
  • 572
  • 2
  • 11
  • 34

2 Answers2

0

In spring-boot you have access EntityManagerFactory as you can check in this datasource configuration but you don't need to use EntityManager directly to interact with database, you can use spring-data-jpa

ValerioMC
  • 2,926
  • 13
  • 24
  • am specifically looking for hibernate integration ,not spring data JPA .Also the example you have mentioned is using custom datasource implementations and session factory implementations. in Spring boot as you know that datasource will be autoconfigured and a JPA variant sessionfactory also autoconfigured . so we dont need to do that custom implementations. – Ansar Samad Jan 25 '19 at 16:52
  • have you tried this solution? https://stackoverflow.com/questions/25063995/spring-boot-handle-to-hibernate-sessionfactory?answertab=active#tab-top – ValerioMC Jan 25 '19 at 21:03
0

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);
    }

}
arseniyandru
  • 760
  • 1
  • 7
  • 16