Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I have to close() every EntityManager?

I have just started migrating my homegrown persistence framework to JPA.

Given that the persistence frameworks hide a lot of the plumbing, I'm interested in knowing if NOT closing EntityManagers will create a resource leak, or if the frameworks will collect and close them for me.

I intend in all places to close them, but do I HAVE to?

At the moment using TopLink, just because it works with NetBeans easily, but am happy to investigate other JPA providers.

like image 212
stevemac Avatar asked Oct 21 '08 00:10

stevemac


People also ask

Is it necessary to close EntityManager?

If you don't close it your entities will be kept as attached, even after you're done using them. Your context will be kept alive even when you can no longer access your EM. The JPA Specification contains more details.

Do we need to close EntityManager in spring boot?

I have used @PersistenceContext to inject Transactional EntityManager to my DAOs and this implies that spring will take care of creating and closing EntityManager for me. However in my previous implementation I used to create and close EntityManager from DAOs, which is now replaced using spring.

What will happen when the clear () of an EntityManager class is invoked?

clear. Clear the persistence context, causing all managed entities to become detached. Changes made to entities that have not been flushed to the database will not be persisted.

When the EntityManager is closed the state of the entity object is removed?

The last state, Detached, represents entity objects that have been disconnected from the EntityManager. For instance, all the managed objects of an EntityManager become detached when the EntityManager is closed.


1 Answers

It depends how you obtained it.

If you created it using EntityManagerFactory you will have to close it no matter what framework you use.

If you obtained it using dependency injection (eg using EJB and @PersistenceContext annotation) you should not close it by hand (AFAIK it will cause RuntimeException).

like image 72
jb. Avatar answered Oct 04 '22 15:10

jb.