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.
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();