且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在entitymanager上使用unwrap方法获得本地hibernate会话后,我是否必须关闭两者?

更新时间:2022-10-15 12:03:13

您不必关闭Session和EntityManger,在hibernate中实际上是hibernate Session。调用unwarp会传递给你底层Session。所以关闭其中一个是好的。

关于连接泄漏,看看我的答案以下问题,也许这是同一个问题。

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?

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.