Should I close () each EntityManager?

I just started migrating my internal save structure to JPA.

Given that persistence structures hide a lot of plumbing, I am interested in finding out if EntityManager does not cover the problem of resource leakage, or if the structures will collect and close them for me.

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

Currently, using TopLink is simply because it works with NetBeans easily, but I am happy to explore other JPA providers.

+61
java jpa toplink persistence
Oct 21 '08 at 0:08
source share
3 answers

It depends on how you received it.

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

If you got it using dependency injection (for example, using the EJB annotation and @PersistenceContext), you should not close it manually (AFAIK raises a RuntimeException).

+70
Oct 21 '08 at 8:23
source share

You should.

Structures have no idea how you intend to use EM, so they cannot close it (with the exception, perhaps, at the end, which is not guaranteed). Yes, without closing them, it will create a drain of resources.

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

In addition, if you plan to write portable code, you should not rely on a particular JPA provider, smart - others may not close EM on time.

+10
October 21 '08 at 1:31
source share

I got EntityManager using @PersistenceContext annotation in my repository. I see that after the connection pools have reached their maxPoolSize , it is not cleared.

However, if I create an EntityManager using EntityManagerFactory and call entitymanager.close() , then the connections are cleared. I use c3p0 as the connection library.

+2
Sep 18 2018-12-18T00: 00Z
source share



All Articles