使用 CDI 在 Java EE 应用程序中获取对 EntityManager 的引用 [英] Getting a reference to EntityManager in Java EE applications using CDI

查看:28
本文介绍了使用 CDI 在 Java EE 应用程序中获取对 EntityManager 的引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是 Java EE 7.我想知道将 JPA EntityManager 注入应用程序范围 CDI bean 的正确方法是什么.您不能只使用 @PersistanceContext 注释注入它,因为 EntityManager 实例不是线程安全的.假设我们希望我们的 EntityManager 在每个 HTTP 请求处理开始时创建,并在 HTTP 请求处理完后关闭.我想到了两个选项:

I'm using Java EE 7. I would like to know what is the proper way to inject a JPA EntityManager into an application scoped CDI bean. You can't just inject it using @PersistanceContext annotation, because EntityManager instances are not thread safe. Let's assume that we want our EntityManager to be created at the beginnig of every HTTP request processing and closed after the HTTP request is processed. Two options come into my mind:

1.创建一个请求范围的 CDI bean,它具有对 EntityManager 的引用,然后将该 bean 注入应用程序范围的 CDI bean.

1. Create a request scoped CDI bean which has a reference to an EntityManager and then inject the bean into an application scoped CDI bean.

import javax.enterprise.context.RequestScoped;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

@RequestScoped
public class RequestScopedBean {

    @PersistenceContext
    private EntityManager entityManager;

    public EntityManager getEntityManager() {
        return entityManager;
    }
}

<小时>

import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;

@ApplicationScoped
public class ApplicationScopedBean {

    @Inject
    private RequestScopedBean requestScopedBean;

    public void persistEntity(Object entity) {
        requestScopedBean.getEntityManager().persist(entity);
    }
}

在此示例中,EntityManager 将在创建 RequestScopedBean 时创建,并在 RequestScopedBean 销毁时关闭.现在我可以将注入移动到某个抽象类以将其从 ApplicationScopedBean 中删除.

In this example an EntityManager will be created when the RequestScopedBean is created, and will be closed when the RequestScopedBean is destroyed. Now I could move the injection to some abstract class to remove it from the ApplicationScopedBean.

2.创建一个生成 EntityManager 实例的生产者,然后将 EntityManager 实例注入到应用程序范围的 CDI bean 中.

2. Create a producer that produces instances of EntityManager, and then inject the EntityManager instance into an application scoped CDI bean.

import javax.enterprise.context.RequestScoped;
import javax.enterprise.inject.Produces;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

public class EntityManagerProducer {

    @PersistenceContext
    @Produces
    @RequestScoped
    private EntityManager entityManager;
}

<小时>

import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import javax.persistence.EntityManager;

@ApplicationScoped
public class ApplicationScopedBean {

    @Inject
    private EntityManager entityManager;

    public void persistEntity(Object entity) {
        entityManager.persist(entity);
    }
}

在本例中,我们还将有一个 EntityManager,它会在每个 HTTP 请求中创建,但是如何关闭EntityManager?处理完HTTP请求后也会关闭吗?我知道 @PersistanceContext 注释注入了容器管理的 EntityManager.这意味着当客户端 bean 被销毁时,EntityManager 将被关闭.在这种情况下,客户端 bean 是什么?是ApplicationScopedBean,在应用程序停止之前永远不会被销毁,还是EntityManagerProducer?有什么建议吗?

In this example we will also have an EntityManager which is created every HTTP request, but what about closing the EntityManager? Will it also be closed after the HTTP request is processed? I know that the @PersistanceContext annotation injects container-managed EntityManager. This means that an EntityManager will be closed when a client bean is destroyed. What is a client bean in this situation? Is it the ApplicationScopedBean, which will never be destroyed until the application stops, or is it the EntityManagerProducer? Any advices?

我知道我可以使用无状态 EJB 而不是应用程序作用域 bean,然后只需通过 @PersistanceContext 注释注入 EntityManager,但这不是重点:)

I know I could use a stateless EJB instead of application scoped bean and then just inject EntityManager by @PersistanceContext annotation, but that's not the point :)

推荐答案

您的 CDI 制作人几乎就对了.唯一的问题是您应该使用生产者方法而不是生产者字段.

You're almost right on with your CDI producer. Only thing is that you should use a producer method instead of a producer field.

如果您使用 Weld 作为 CDI 容器(GlassFish 4.1 和 WildFly 8.2.0),那么您结合 @Produces@PersistenceContext 的示例生产者字段上的@RequestScoped应该在部署期间抛出这个异常:

If you're using Weld as CDI container (GlassFish 4.1 and WildFly 8.2.0), then your example of combining @Produces, @PersistenceContext and @RequestScoped on a producer field should throw this exception during deployment:

org.jboss.weld.exceptions.DefinitionException: WELD-001502:资源生产者字段 [Resource Producer Field [EntityManager] 与限定符 [@Any @Default] 声明为 [[BackedAnnotatedField]@Produces @RequestScoped @PersistenceContextcom.somepackage.EntityManagerProducer.entityManager]] 必须是@Dependent 作用域

org.jboss.weld.exceptions.DefinitionException: WELD-001502: Resource producer field [Resource Producer Field [EntityManager] with qualifiers [@Any @Default] declared as [[BackedAnnotatedField] @Produces @RequestScoped @PersistenceContext com.somepackage.EntityManagerProducer.entityManager]] must be @Dependent scoped

事实证明,在使用生产者字段查找 Java EE 资源时,容器不需要支持除@Dependent 之外的任何其他范围.

Turns out that the container is not required to support any other scope than @Dependent when using a producer field to lookup Java EE resources.

CDI 1.2,第 3.7 节.资源:

CDI 1.2, section 3.7. Resources:

容器不需要支持其他范围的资源比@Dependent.便携式应用程序不应定义资源除了@Dependent 之外的任何范围.

The container is not required to support resources with scope other than @Dependent. Portable applications should not define resources with any scope other than @Dependent.

这句话是关于生产者字段的.使用生产者方法查找资源是完全合法的:

This quote was all about producer fields. Using a producer method to lookup a resource is totally legit:

public class EntityManagerProducer {

    @PersistenceContext    
    private EntityManager em;

    @Produces
    @RequestScoped
    public EntityManager getEntityManager() {
        return em;
    }
}

首先,容器将实例化生产者,并将容器管理的实体管理器引用注入到 em 字段中.然后容器将调用您的生产者方法并将他返回的内容包装在请求范围的 CDI 代理中.这个 CDI 代理是你的客户端代码在使用 @Inject 时得到的.因为生产者类是@Dependent(默认),底层容器管理的实体管理器引用不会被任何其他产生的 CDI 代理共享.每次另一个请求需要实体管理器时,生产者类的一个新实例将被实例化,一个新的实体管理器引用将被注入生产者,而生产者又被包装在一个新的 CDI 代理中.

First, the container will instantiate the producer and a container-managed entity manager reference will be injected into the em field. Then the container will call your producer method and wrap what he returns in a request scoped CDI proxy. This CDI proxy is what your client code get when using @Inject. Because the producer class is @Dependent (default), the underlying container-managed entity manager reference will not be shared by any other CDI proxies produced. Every time another request want the entity manager, a new instance of the producer class will be instantiated and a new entity manager reference will be injected into the producer which in turn is wrapped in a new CDI proxy.

从技术上讲,将资源注入字段 em 的底层和未命名容器允许重用旧的实体管理器(参见 JPA 2.1 规范中的脚注,部分7.9.1 Container责任",第 357 页).但到目前为止,我们尊重 JPA 要求的编程模型.

To be technically correct, the underlying and unnamed container who do the resource injection into the field em is allowed to reuse old entity managers (see footnote in JPA 2.1 specification, section "7.9.1 Container Responsibilities", page 357). But so far, we honor the programming model required by JPA.

在前面的示例中,您标记 EntityManagerProducer @Dependent 还是 @RequestScoped 都没有关系.使用@Dependent 在语义上更正确.但是如果你在生产者类上放置比请求范围更广的范围,你就有可能将底层实体管理器引用暴露给许多线程,我们都知道这不是一件好事.底层实体管理器实现可能是线程本地对象,但可移植应用程序不能依赖于实现细节.

In the preceding example, it would not matter if you mark EntityManagerProducer @Dependent or @RequestScoped. Using @Dependent is semantically more correct. But if you put a wider scope than request scope on the producer class you risk exposing the underlying entity manager reference to many threads which we both know is not a good thing to do. The underlying entity manager implementation is probably a thread-local object, but portable applications cannot rely on implementation details.

CDI 不知道如何关闭您放入请求绑定上下文中的任何内容.最重要的是,容器管理的实体管理器不能被应用程序代码关闭.

CDI does not know how to close whatever stuff it is that you put into the request bound context. More so than anything else, a container-managed entity manager must not be closed by application code.

JPA 2.1,7.9.1 容器职责"部分:

JPA 2.1, section "7.9.1 Container Responsibilities":

容器必须抛出 IllegalStateException 如果应用程序在容器管理的实体管理器上调用 EntityManager.close.

The container must throw the IllegalStateException if the application calls EntityManager.close on a container-managed entity manager.

不幸的是,许多人确实使用 @Disposes 方法来关闭容器管理的实体管理器.当 Oracle 提供的官方 Java EE 7 教程时,谁能责怪他们以及 CDI 规范 本身使用处置器来关闭容器管理的实体经理.这是完全错误的,无论您将调用放在哪里,在处理程序方法中还是在其他地方,对 EntityManager.close() 的调用都会抛出一个 IllegalStateException.Oracle 示例是两者中最大的罪魁祸首,将生产者类声明为 @javax.inject.Singleton.正如我们所了解到的,这种风险将底层实体管理器的引用暴露给许多不同的线程.

Unfortunately, many people do use a @Disposes method to close the container-managed entity manager. Who can blame them when the official Java EE 7 tutorial provided by Oracle as well as the CDI specification itself use a disposer to close a container-managed entity manager. This is simply wrong and the call to EntityManager.close() will throw a IllegalStateException no matter where you put that call, in a disposer method or somewhere else. The Oracle example is the biggest sinner of the two by declaring the producer class to be a @javax.inject.Singleton. As we learned, this risk exposing the underlying entity manager reference to many different threads.

已经证明 此处 错误地使用 CDI 生产者和处置器,1) 非线程安全的实体管理器可能会泄露给许多线程,2) 处置器不起作用;让实体管理器保持打开状态.发生的事情是容器吞下的 IllegalStateException,没有留下任何痕迹(创建了一个神秘的日志条目,表明销毁实例时出错").

It has been proven here that by using CDI producers and disposers wrongfully, 1) the not thread-safe entity manager may be leaked to many threads and 2) the disposer has no effect; leaving the entity manager open. What happened was the IllegalStateException which the container swallowed leaving no trace of it (a mysterious log entry is made which says there was an "error destroying an instance").

通常,使用 CDI 查找容器管理的实体管理器并不是一个好主意.应用程序最有可能只使用 @PersistenceContext 并且对它感到满意.但是,在您的示例中,规则总是有例外的,在处理应用程序管理的实体管理器的生命周期时,CDI 也可以用于抽象 EntityManagerFactory.

Generally, using CDI to lookup container-managed entity managers is not a good idea. The application is most likely better off just using @PersistenceContext and be happy with it. But there are always exceptions to the rule like in your example, and CDI can also be useful to abstract away the EntityManagerFactory when handling the life cycle of application-managed entity managers.

要全面了解如何获取容器管理的实体管理器以及如何使用 CDI 查找实体管理器,您可能需要阅读 this这个.

To get a complete picture on how to obtain a container-managed entity manager and how to use CDI to lookup entity managers, you might want to read this and this.

这篇关于使用 CDI 在 Java EE 应用程序中获取对 EntityManager 的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆