Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should we close the EntityManagerFactory?

I am pretty new on the ORM's. I just start to read books and documents about Java Persistence API with Hibernate.

I just wondered, closing EntityManagerFactory is similar with jdbc database connection closing?

Should we close it after every persist/update/delete or not? If we don't close it, will the database connection stay opened?

like image 978
Tim Tuckle Avatar asked Jul 28 '10 06:07

Tim Tuckle


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.

What is the use of EntityManagerFactory?

In JPA, the EntityManager interface is used to allow applications to manage and search for entities in the relational database. The EntityManager is an API that manages the lifecycle of entity instances. An EntityManager object manages a set of entities that are defined by a persistence unit.

Is EntityManagerFactory thread safe?

EntityManagerFactory instances are thread-safe. Applications create EntityManager instances in this case by using the createEntityManager method of javax. persistence.

What is difference between EntityManagerFactory and SessionFactory?

Using EntityManagerFactory approach allows us to use callback method annotations like @PrePersist, @PostPersist,@PreUpdate with no extra configuration. Using similar callbacks while using SessionFactory will require extra efforts. Related Hibernate docs can be found here and here.


1 Answers

I just wondered, closing EntityManagerFactory is similar with jdbc database connection closing?

This is not exactly true but closing an EntityManagerFactory would be closer to destroying a whole connection pool. If you want to think JDBC connection, you should think EntityManager.

Should we close it after every persist/update/delete or not?

Creating an EntityManagerFactory is a pretty expensive operation and should be done once for the lifetime of the application (you close it at the end of the application). So, no, you should not close it for each persist/update/delete operation.

The EntityManagerFactory is created once for all and you usually get an EntityManager per request, which is closed at the end of the request (EntityManager per request is the most common pattern for a multi-user client/server application).

If we don't close it, will the database connection stay opened?

As hinted, it's the EntityManager that is actually associated to a database connection and closing the EntityManager will actually release the JDBC connection (most often, return it to a pool).

like image 149
Pascal Thivent Avatar answered Oct 02 '22 17:10

Pascal Thivent