12

I've created a spring boot application, and I want to handle the Hibernate SessionFactory, so in my service class, I can just call the Hibernate SessionFactory as following :

@Autowired
private SessionFactory sessionFactory;

I found a similar question in stackoverflow where I have to add the following line in application.properties :

spring.jpa.properties.hibernate.current_session_context_class=org.springframework.orm.hibernate4.SpringSessionContext

but I'm getting this error :

Cannot resolve property 'current_session_context_class' in java.lang.String

How can I solve this ?

pom.xml dependencies :

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
    </dependencies>
Community
  • 1
  • 1
Renaud is Not Bill Gates
  • 1,684
  • 34
  • 105
  • 191

2 Answers2

18

Since version 2.0, JPA provides easy access to the APIs of the underlying implementations. The EntityManager and the EntityManagerFactory provide an unwrap method which returns the corresponding classes of the JPA implementation.

In the case of Hibernate, these are the Session and the SessionFactory.

SessionFactory sessionFactory = entityManagerFactory.unwrap(SessionFactory.class);
Nicolas Filotto
  • 43,537
  • 11
  • 94
  • 122
Karim M. Fadel
  • 338
  • 1
  • 8
  • 3
    Your solution will throw a: java.lang.NullPointerException: null. entityManagerFactory.unwrap(SessionFactory.class) has to be called when needed it. Also I'm used to old Transaction manager and I had to change the classic sessionFactory.getCurrentTransaction(); to sessionFactory.openTransaction(); I'm really hoping it won't ignore the Spring managed transaction. – White_King Jan 31 '19 at 07:44
  • 1
    This API has changed. You now need to use `Session session = entityManager.unwrap(Session.class); SessionFactory sessionFactory = session.getSessionFactory()` – kapad May 27 '19 at 01:24
5

Try enabling HibernateJpaSessionFactoryBean in your Spring configuration.

@Bean
public HibernateJpaSessionFactoryBean sessionFactory() {
    return new HibernateJpaSessionFactoryBean();
}

Have a look at: https://stackoverflow.com/a/33881946/676731

By Spring configuration I mean a class annotated with @Configuration annotation or @SpringBootApplication (it is implicitly annotated with @Configuration).

Nicolas Filotto
  • 43,537
  • 11
  • 94
  • 122
BartoszMiller
  • 1,245
  • 1
  • 15
  • 24