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