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

12,289

Solution 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.

Solution 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();
Share:
12,289
benstpierre
Author by

benstpierre

My entire career has been building commercial software mostly in Java and C#. I have working with a dozen other languages but I really love working in these two the most. Recently I have been writing application in Vaadin and think it's the best thing since sliced bread.

Updated on June 15, 2022

Comments

  • benstpierre
    benstpierre almost 2 years

    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?