Best practice for open / get Hibernate session in Spring 4 + Hibernate 4.3.1.final

In our project, we use Spring and Spring Data (for the server-side API service), but sometimes we make a request, not using Spring Data, but using JPA criteria. For this we use:

@PersistenceContext private EntityManager em; ... CriteriaBuilder cb = em.getCriteriaBuilder(); ... 

From Spring docs:

Although EntityManagerFactory instances are thread safe, EntityManager instances are not. The introduced JPA EntityManager behaves like an EntityManager extracted from the application server JNDI environment, as defined by the JPA specification. It delegates all calls to the current transactional EntityManager, if any; otherwise, it returns to the newly created EntityManager for the operation, effectively making its use safe for threads.

So, it seems that the way we use should get the current session, if it exists, and if it should not create a new one. The problem we are facing is a memory leak from this use. seems to open many Hibernate sessions this way and not close them.

So for the question: What is the best practice of getCurrent / open new session in Spring with Hibernate?


Note: HibernateUtil does not have getSessionFactory() , as suggested in some other posts.

Thanks,

Alon

+1
source share

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


All Articles