java 我们什么时候应该关闭 EntityManagerFactory?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3350483/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
When should we close the EntityManagerFactory?
提问by Tim Tuckle
I am pretty new on the ORM's. I just start to read books and documents about Java Persistence API with Hibernate.
我对 ORM 很陌生。我刚开始阅读关于 Java Persistence API with Hibernate 的书籍和文档。
I just wondered, closing EntityManagerFactory is similar with jdbc database connection closing?
我只是想知道,关闭 EntityManagerFactory 与关闭 jdbc 数据库连接类似吗?
Should we close it after every persist/update/delete or not? If we don't close it, will the database connection stay opened?
我们是否应该在每次持久/更新/删除后关闭它?如果我们不关闭它,数据库连接会保持打开状态吗?
回答by Pascal Thivent
I just wondered, closing
EntityManagerFactoryis similar with jdbc database connection closing?
我只是想知道,关闭
EntityManagerFactory与 jdbc 数据库连接关闭类似吗?
This is not exactly true but closing an EntityManagerFactorywould be closer to destroying a whole connection pool. If you want to think JDBC connection, you should think EntityManager.
这并不完全正确,但关闭一个EntityManagerFactory更接近于破坏整个连接池。如果您想考虑 JDBC 连接,您应该考虑EntityManager.
Should we close it after every persist/update/delete or not?
我们是否应该在每次持久/更新/删除后关闭它?
Creating an EntityManagerFactoryis a pretty expensive operation and should be done once for the lifetime of the application (you closeit at the end of the application). So, no, you should not close it for each persist/update/delete operation.
创建EntityManagerFactory一个非常昂贵的操作,应该在应用程序的生命周期内完成一次(在应用程序close结束时完成)。所以,不,你不应该为每个持久/更新/删除操作关闭它。
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).
它EntityManagerFactory是一次性创建的,您通常会得到一个EntityManager每个请求,它在请求结束时关闭(EntityManager每个请求是多用户客户端/服务器应用程序的最常见模式)。
If we don't close it, will the database connection stay opened?
如果我们不关闭它,数据库连接会保持打开状态吗?
As hinted, it's the EntityManagerthat is actually associated to adatabase connection and closing the EntityManagerwill actually release the JDBC connection (most often, return it to a pool).
作为暗示,它的EntityManager,实际上是关联到一个数据库连接和关闭EntityManager将真正释放JDBC连接(最常见的,其返回到池)。

