Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access SessionFactory from Spring Boot Application

I am trying to get access to the Hibernate session factory but am getting the following error at the line mentioned.

No CurrentSessionContext configured!

code

@Service
@Transactional
public class GenericSearchImpl implements GenericSearch {

    @Autowired
    private EntityManagerFactory entityManagerFactory;

    @Override
    @SuppressWarnings("unchecked")
    public <T> List<T> search(final Class<T> type, final String[] criteriaList, final int page, final int perPage) {
        Session session = getSession();
        ...
    }

    public Session getSession() {
        final HibernateEntityManagerFactory emFactory = (HibernateEntityManagerFactory) entityManagerFactory;
        final SessionFactory sessionFactory = emFactory.getSessionFactory(); 
        return sessionFactory.getCurrentSession(); //ERROR No CurrentSessionContext configured!

          //This worked but I understand it to be BAD as spring should be managing open sessions.
          //        try {
          //            return sessionFactory.getCurrentSession();
          //        } catch (Exception e) {
          //            return sessionFactory.openSession();
          //        }
    }

    ...

}

Any idea why?

like image 689
jax Avatar asked Mar 24 '15 06:03

jax


1 Answers

In property file,

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

in configuration class

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

Then you can autowire

@Autowired
private SessionFactory sessionFactory;

We do this as Spring boot doesn't auto configure hibernate sessinoFactory.

Update: As of Spring 4.3.12 and Hibernate 5.2, above Hibernate API solution is depreciated in favor of generic JPA API solution EntityManagerFactory.

Session session = entityManager.unwrap(Session.class);

Here is some detailed example doc with examples on EntityManagerFactory.

like image 129
Anand Avatar answered Sep 26 '22 20:09

Anand