在entitymanager上使用unwrap方法获取本机hibernate会话后,我必须关闭它们吗?

ben*_*rre 5 hibernate entitymanager

我的代码看起来像这样.

 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();
 }
Run Code Online (Sandbox Code Playgroud)

但我似乎在某个地方有连接泄漏.我想知道我是否应该关闭entityManager和hibernateSession.还有其他人在这种情况下工作过吗?

小智 1

我不了解 Hibernate,但在 EclipseLink 中,他们特别指出,在通过 unwrap 检索连接之前,您必须处于事务中:

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

所以试试这个:

entityManager.getTransaction.begin();
this.hibernateSession = entityManager.unwrap(Session.class);
...
entityManager.getTransaction.commit();
Run Code Online (Sandbox Code Playgroud)