Access SessionFactory from Spring Boot Application

I am trying to access a Hibernate factory session, but am getting the following error on the specified line.

No CurrentSessionContext configured! 

the 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?

+5
source share
2 answers

In the properties 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 autwire

 @Autowired private SessionFactory sessionFactory; 

We do this because Spring boot is not configured automatically for hibernate sessinoFactory.

+7
source

You can access the SessionFactory using the entityManagerFactory deployment method instead of HibernateJpaSessionFactoryBean

 SessionFactory sessionFactory = entityManagerFactory.unwrap(SessionFactory.class); 

HibernateJpaSessionFactoryBean deprecated in Spring Boot 1.5.8

+1
source

Source: https://habr.com/ru/post/1215971/


All Articles