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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With