Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 609
benstpierre Avatar asked Jan 18 '13 15:01

benstpierre


2 Answers

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.

like image 136
Haim Raman Avatar answered Oct 10 '22 08:10

Haim Raman


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();
like image 39
entreprenr Avatar answered Oct 10 '22 09:10

entreprenr