Do I have to close() every EntityManager?
Asked Answered
E

4

78

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.

Evaluate answered 21/10, 2008 at 0:8 Comment(1)
See also Should the JPA entity manager be closed?Proclaim
A
96

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

Annulet answered 21/10, 2008 at 8:23 Comment(1)
In a wider sense the EM still should be closed. It's just the work is done for you by EJB, and you make it possible by adhering to EJB requirements.Impassioned
I
11

You should.

Frameworks have no idea how you intend to use the EM, so they cannot close it (except, may be, on finalization, which is not guaranteed). Yes, not closing them would create a resource leak.

The idea is the same as "always close java.sql.Connection" (despite some data sources have settings to close them automatically by inactivity) or "always close Hibernate session".

Besides, if you plan to write portable code, you shouldn't rely on specific JPA provider "being smart" -- other may fail to close the EM in time.

Impassioned answered 21/10, 2008 at 1:31 Comment(0)
B
5

I have obtained EntityManager using @PersistenceContext annotation in my repository. I can see that after the connectionpools reaches its maxPoolSize it does not get cleaned up.

However if I create EntityManager using EntityManagerFactory and call entitymanager.close() then connections are getting cleaned up. I am using c3p0 as connectionpool library.

Burka answered 18/9, 2012 at 9:42 Comment(0)
P
0

Justo to give my 5 cents you must remember to close your EntityManagerFactory. I was just using it to create my EntityManager and it opened and kept opend a new conection pool every time.

Preterhuman answered 20/5, 2022 at 19:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.