Java 我是否必须关闭()每个 EntityManager?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/220374/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 11:35:50  来源:igfitidea点击:

Do I have to close() every EntityManager?

javajpapersistencetoplink

提问by stevemac

I have just started migrating my homegrown persistence framework to JPA.

我刚刚开始将我自己开发的持久性框架迁移到 JPA。

Given that the persistence frameworks hide a lot of the plumbing, I'm interested in knowing if NOT closing EntityManagers will create a resource leak, or if the frameworks will collect and close them for me.

鉴于持久性框架隐藏了很多管道,我想知道不关闭 EntityManager 是否会造成资源泄漏,或者框架是否会为我收集和关闭它们。

I intend in all places to close them, but do I HAVE to?

我打算在所有地方关闭它们,但我必须这样做吗?

At the moment using TopLink, just because it works with NetBeans easily, but am happy to investigate other JPA providers.

目前使用 TopLink,只是因为它很容易与 NetBeans 配合使用,但我很高兴调查其他 JPA 提供程序。

采纳答案by jb.

It depends how you obtained it.

这取决于你如何获得它。

If you created it using EntityManagerFactory you will have to close it no matter what framework you use.

如果您使用 EntityManagerFactory 创建它,无论您使用什么框架,您都必须关闭它。

If you obtained it using dependency injection (eg using EJB and @PersistenceContext annotation) you should not close it by hand (AFAIK it will cause RuntimeException).

如果您使用依赖注入(例如使用 EJB 和 @PersistenceContext 注释)获得它,则不应手动关闭它(AFAIK 它将导致 RuntimeException)。

回答by Vladimir Dyuzhev

You should.

你应该。

Frameworks have no idea how you intend to use the EM, so they cannot close it (except, may be, on finalization, which is not guaranteed). Yes, not closing them would create a resource leak.

框架不知道您打算如何使用 EM,因此它们无法关闭它(除非可能是在最终确定时,这不能保证)。是的,不关闭它们会造成资源泄漏。

The idea is the same as "always close java.sql.Connection" (despite some data sources have settings to close them automatically by inactivity) or "always close Hibernate session".

这个想法与“始终关闭 java.sql.Connection”(尽管某些数据源具有在不活动时自动关闭它们的设置)或“始终关闭 Hibernate 会话”相同。

Besides, if you plan to write portable code, you shouldn't rely on specific JPA provider "being smart" -- other may fail to close the EM in time.

此外,如果您打算编写可移植的代码,您不应该依赖特定的 JPA 提供者“聪明”——其他人可能无法及时关闭 EM。

回答by Puneet

I have obtained EntityManagerusing @PersistenceContextannotation in my repository. I can see that after the connectionpools reaches its maxPoolSizeit does not get cleaned up.

我已经在我的存储库中EntityManager使用了@PersistenceContext注释。我可以看到在连接池到达它之后maxPoolSize它没有被清理。

However if I create EntityManagerusing EntityManagerFactoryand call entitymanager.close()then connections are getting cleaned up. I am using c3p0as connectionpool library.

但是,如果我创建EntityManagerusingEntityManagerFactory并调用,entitymanager.close()则连接将被清理。我正在c3p0用作连接池库。