Do I have to close() every EntityManager?

stevemac picture stevemac · Oct 21, 2008 · Viewed 54.3k times · Source

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.

Answer

jb. picture jb. · Oct 21, 2008

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