繁体   English   中英

实例化JPA管理器bean的“正确”方法?

[英]The 'correct' way to instantiate JPA manager bean?

我正在使用IBM RAD开发一些JPA实体,并从中开发相应的JPA Manager Bean。 Manager Bean(由RAD生成)具有以下成员:

@PersistenceUnit
private EntityManagerFactory emf;

我不确定如何从无状态EJB(3.0)中实例化此管理器bean(或对其进行引用),因此我在管理器bean中添加了一个构造函数,可以在其中传递EntityManagerFactory实例。 我通过使用`@PersistenceUnit'注释获得对EJB中EntityManagerFactory的引用,如下所示:

@PersistenceUnit
private EntityManagerFactory _entityManagerFactory;

这似乎是不必要的,我相信必须有一种方法可以告诉容器(以我的情况为Websphere 7.0)以某种方式“引导”该容器,以便立即获得对JPA管理器bean的引用。 是吗?

更新:看来我还没有足够详尽的介绍。 抱歉

  • 涉及三个对象:JPA实体,JPA实体管理器和无状态EJB。
  • JPA实体管理器类(不是EJB)是由RAD创建的,并且具有便利的方法(命名查询)。 它还定义了成员@PersistenceUnit private EntityManagerFactory emf 我知道我可以直接使用EntityManager ,但是我想使用MyEntityManager作为其便捷方法。
  • 通过使用上述注释,我可以在无状态EJB中获得对EntityManager或EntityManagerFactory的引用(也像Bozho建议的那样)
  • 我想在无状态EJB中获得对JPA实体管理器的引用。 如果我将其“新建”(新的MyEntityManager()),则emf字段为null。 解决方法是在EJB中声明@PersistenceUnit字段,然后将其传递给JPA实体管理器并使用它。
  • 想一想,也许我可以将JPA实体管理器声明为EJB并完成它……(尽管这似乎又是不必要的)。 我以为PersistenceContext.getJpaManager(MyEntityManager.class)可能存在一种方法,我也许会错过它。
@PersistenceContext
private EntityManager em;

看来您有要注入其他Bean的自定义Bean(至少需要一个本地接口):

@EJB
private MyEntityManager em;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM