Search code examples
javajpapersistencetoplink

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.


Solution

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