问题
In our project we use Spring and Spring Data (for server side API service), but sometimes we do query not using Spring Data, but using JPA criteria. In order to do so we use:
@PersistenceContext
private EntityManager em;
...
CriteriaBuilder cb = em.getCriteriaBuilder();
...
From the Spring
docs:
Although EntityManagerFactory instances are thread-safe, EntityManager instances are not. The injected JPA EntityManager behaves like an EntityManager fetched from an application server's JNDI environment, as defined by the JPA specification. It delegates all calls to the current transactional EntityManager, if any; otherwise, it falls back to a newly created EntityManager per operation, in effect making its usage thread-safe.
So it seems that the way we use should get the current session if exists and if not should create new one. The issue we are facing is a memory leak of this use. seems like this way opens a lot of Hibernate session and does not close them.
So for the question: What is the best practice to getCurrent/open new session in Spring with Hibernate?
Note: HibernateUtil
does not have getSessionFactory()
as suggested in some other posts
Thanks,
Alon
来源:https://stackoverflow.com/questions/21696181/best-practice-for-open-get-hibernate-session-in-spring-4-hibernate-4-3-1-final