After using the unwrap method on entitymanager to get the native hibernate session do I have to close both?

时光毁灭记忆、已成空白 提交于 2019-12-07 04:10:15

问题


I have code that looks like this.

 this.entityManager = AppFactory.instance().getEntityManagerFactory().createEntityManager();
 this.hibernateSession = entityManager.unwrap(Session.class);
 try{
 //do some queries using both entityManager and hibernateSession
 }finally{
 this.entityManager.close();
 }

But I seem to have a connection leak somewhere. I'm wondering if I am supposed to close both entityManager and hibernateSession. Has anybody else worked with this type of situation?


回答1:


You do not have to close both Session and EntityManger, under the hood EntityManger in hibernate is actually hibernate Session. Calling unwarp will pass you the underlying Session. So closing one of them is fine.
Regarding the connection leak, look at my answer to the following question, maybe it’s the same issue.




回答2:


I don't know about Hibernate, but in EclipseLink they say specifically that you have to be in a transaction before retrieving the Connection via unwrap:

http://wiki.eclipse.org/EclipseLink/Examples/JPA/EMAPI#JPA_2.0

so try this:

entityManager.getTransaction.begin();
this.hibernateSession = entityManager.unwrap(Session.class);
...
entityManager.getTransaction.commit();


来源:https://stackoverflow.com/questions/14402330/after-using-the-unwrap-method-on-entitymanager-to-get-the-native-hibernate-sessi

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