When should we close the EntityManagerFactory?

后端 未结 1 1803
伪装坚强ぢ
伪装坚强ぢ 2021-01-31 03:51

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 simi

相关标签:
1条回答
  • 2021-01-31 04:20

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

    0 讨论(0)
提交回复
热议问题