When should we close the EntityManager and EntityManagerFactory
For EntityManager:
It depends on 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.
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).
For EntityManagerFactory:
Closing an EntityManagerFactory would be closer to destroying a whole connection pool. If you want to think JDBC connection, you should think EntityManager.
We should not close the factory after every operation.
Creating an EntityManagerFactoryis a pretty expensive operation and should be done once for the lifetime of the application (you
The EntityManagerFactoryis created once for all and you usually get an EntityManagerper request, which is closed at the end of the request (EntityManagerper request is the most common pattern for a multi-user client/server application).
It depends on 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.
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).
For EntityManagerFactory:
Closing an EntityManagerFactory would be closer to destroying a whole connection pool. If you want to think JDBC connection, you should think EntityManager.
We should not close the factory after every operation.
Creating an EntityManagerFactoryis 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 EntityManagerFactoryis created once for all and you usually get an EntityManagerper request, which is closed at the end of the request (EntityManagerper request is the most common pattern for a multi-user client/server application).
留言
張貼留言