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?
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.
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.
EntityManagerFactory instances are thread-safe. Applications create EntityManager instances in this case by using the createEntityManager method of javax. persistence.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With