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

。_饼干妹妹 提交于 2019-12-24 15:26:32

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!