gpt4 book ai didi

jakarta-ee - Java EE 容器是否会自动关闭注入(inject)的 EntityManagerFactory?

转载 作者:行者123 更新时间:2023-12-01 05:14:21 25 4
gpt4 key购买 nike

假设我在 @Stateless Enterprise JavaBean 中有这段代码:

@PersistenceUnit
EntityManagerFactory emf;

Java EE 容器会自动关闭我的 EntityManagerFactory迟早?

规范说明了什么

Java Persistence specification, version 2.1在第 338 页上说:

When the application has finished using the entity manager factory, and/or at application shutdown, the application should close the entity manager factory.



好的,这很简单。我必须关闭工厂。

但是,由于我首先注入(inject)了工厂,所以我有点紧张自己调用 close() 方法。如果容器并不比在下一个想要工厂的 bean 中重用一个封闭的工厂更聪明怎么办?此外,我不喜欢添加很多管道来将我自己的逻辑与应用程序关闭时发生或不发生的情况 Hook 。此外,我没有打开/创建工厂只是闻起来很糟糕,但我的代码负责关闭它。对于这个问题,大量的 Java EE 规范肯定有更多要告诉我的吗?

嗯.. 没有 .我在 JPA 2.1 和 EJB 3.2 中看到的示例注入(inject)工厂的规范不会明确关闭它。这些示例只有在通过 Persistence.createEntityManagerFactory() 显式创建工厂时才会关闭它。 (参见 JPA 2.1 规范,第 345 和 355 页)。

我看到的关于容器职责的唯一讨论来自 JPA 2.1 规范第 356 页:

[..] the container is required to support third-party persistence providers, and in this case the container must use the PersistenceProvider.createContainerEntityManagerFactory method to create the entity manager factory and the EntityManagerFactory.close method to destroy the entity manager factory prior to shutdown (if it has not been previously closed by the application).



这里说容器确实有责任关闭工厂。但是让我几乎不相信最后这句话的是,示例/引用清楚地谈到了容器使用“第三方持久性提供程序”时的一个非常特殊的用例。

对我来说,如果我阅读从第 286 页开始的 EJB 3.2 规范中关于持久性单元引用的章节,这个话题会变得更加困惑。在这里,没有关于谁负责关闭实体管理器工厂的消息 - 我或容器。

我的结论是,通过复制规范中使用的示例,我应该或者更确切地说必须是安全的。这意味着我不必明确关闭工厂。不过,让我感到困惑的是,我在 JPA 规范中使用的第一句话清楚地表明我必须关闭工厂!

你有什么意见?我错过了什么吗?

最佳答案

由于EntityManagerFactory由您的容器创建,它负责其生命周期(并因此关闭它)。只有一个EMF ,因此除非在应用程序生命周期结束时关闭它,否则将毫无意义。来自 JPA 2.1 spec第 9.1 节:

[...]

The EntityManagerFactory instance obtained as a result will be used by the container to create container-managed entity managers. Only one EntityManagerFactory is permitted to be created for each deployed persistence unit configuration. Any number of EntityManager instances may be created from a given factory.



但是,您有责任关闭您的 EntityManager如果您决定通过注入(inject)的 EMF 自己管理它.

关于jakarta-ee - Java EE 容器是否会自动关闭注入(inject)的 EntityManagerFactory?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22117555/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com