简体   繁体   English

在Java EE中与EJB交互的最佳方式

[英]Best way to interact with EJBs in Java EE

I have a moderate sized Java EE 6 project that uses several EJBs, including one which sole purpose is managing database calls through JPA. 我有一个中等规模的Java EE 6项目,它使用多个EJB,其中一个目的是通过JPA管理数据库调用。 My question is what is the best way to add a new class that does some random bit of functionality and then calls the database access EJB to persist the data from this class. 我的问题是添加一个新类的最佳方法是什么,该类执行一些随机功能,然后调用数据库访问EJB来保存此类中的数据。

Does this new class have to be an EJB if it needs access to annotations and injections? 如果需要访问注释和注入,这个新类必须是EJB吗? Does it have to be an EJB if it has to be deployed with the rest of the project? 如果必须与项目的其余部分一起部署,它是否必须是EJB?

I was told that if you want to add a new logic class to the project it either has to be an EJB or you can remotely integrate it using JNDI to access EJB elements and create some kind of client interface. 有人告诉我,如果你想为项目添加一个新的逻辑类,它必须是一个EJB,或者你可以使用JNDI远程集成它来访问EJB元素并创建某种客户端接口。 Right now my new class is just a POJO but it's not able to access the EJB functionality. 现在我的新类只是一个POJO,但它无法访问EJB功能。

What should I do in general? 一般我该怎么办?

EDIT: Please note my question IS NOT about database access. 编辑:请注意我的问题不是数据库访问。 That's just an example I'm using. 这只是我正在使用的一个例子。 My guestion is more broad. 我的猜测更广泛。 I want to know how to access EJB methods from other classes I create. 我想知道如何从我创建的其他类访问EJB方法。 From one EJB to another you can simply inject the other EJB since they're both container managed. 从一个EJB到另一个EJB,您可以简单地注入另一个EJB,因为它们都是容器管理的。 But say I create another class in the same package as the EJBs how might How can I access those methods? 但是说我在与EJB相同的包中创建另一个类如何才能访问这些方法? Is it possbile? 可能吗? What is the best practices here. 这里的最佳做法是什么?

Right now I have a class that is taking twitter feed data from a URL it then parses the JSON and returns a string of the top 10 entries. 现在我有一个类从URL获取twitter feed数据,然后解析JSON并返回前10个条目的字符串。 I want to call my EJB that manages database access and pass that string to its corresponding method but I cannot do that because my class is not also an EJB. 我想调用管理数据库访问的EJB并将该字符串传递给相应的方法,但我不能这样做,因为我的类不是EJB。

EJBs are generally used to implement services of any kind. EJB通常用于实现任何类型的服务。 They integrate really well with JPA so are often used for DB access, but that's not their only usage. 它们与JPA很好地集成,因此通常用于数据库访问,但这不是它们的唯一用途。

What EJBs are typically not suited for is modeling data. 什么EJB通常适合建模数据。 Ie they should be the verbs in your application, not the nouns. 即它们应该是你的应用程序中的动词,而不是名词。 The following is thus wrong : 以下是错误的

@Stateless
@Entity
public class CreditCard { // silly, don't do this!

     @Id
     Long id; + getters/setters
     Data expiration date; + getters/setters
}

The following is better, it's a service that when your application starts up fetches some quote data from somewhere: 以下是更好的,它是一个服务,当您的应用程序启动时从某个地方获取一些引用数据:

@Singleton
@Startup
public class QuoteFetcher {

     private List<Quote> quotes; // + getter

     @PostConstruct
     public fetchQuote()
          quotes = SomeUrlBuilder.someUrl().getQuotes();
     }
 }

The following is the obligatory DAO example: 以下是强制性DAO示例:

@Stateless
public class JPAInvoiceDAO implements InvoiceDAO {

     @PersistenceContext
     private EntityManager entityManager;

     public Invoice getById(Long invoiceId) {
           return entityManager.find(invoiceId, Invoice.class);
     }

     // More DAO methods
}

The following shows how declarative security is used, and how a bean looks up something that has been externally mapped into its private context (ENC): 下面显示了如何使用声明性安全性,以及bean如何查找已外部映射到其私有上下文(ENC)的内容:

@Stateless
public class TokenFetcher

    @Resource
    private SessionContext sessionContext;

    @RolesAllowed("SYSTEM")
    public Token getToken() {
        return (Token) sessionContext.lookup("token");
    }
}

The second part of the question seems to be how to use these beans in your code. 问题的第二部分似乎是如何在代码中使用这些bean。 There are basically four methods: 基本上有四种方法:

  1. Injection in managed beans 在托管bean中注入
  2. Bootstrapping via JNDI 通过JNDI引导
  3. Automatically called at startup 在启动时自动调用
  4. Automatically via a timer 通过计时器自动

Injection is the easiest way, but only managed beans are injection candidates (basically meaning the Java EE framework creates the bean, and you don't use new() to instantiate it). 注入是最简单的方法,但只有托管bean是注入候选者(基本上意味着Java EE框架创建bean,而不使用new()来实例化它)。

Eg Injection: 例如注射:

@ManagedBean
public class InvoiceBacking {

     private Long invoiceId; // + getter/setter
     private Invoice invoice; // + getter

     @EJB
     private InvoiceDAO invoiceDAO;

     @PostConstruct
     public void init() {
          invoice = invoiceDAO.getById(invoiceId);
     }
 }

(also see Communication in JSF 2.0#Processing GET request parameters ) (另请参阅JSF 2.0中的通信#处理GET请求参数

Bootstrapping via JNDI: 通过JNDI引导:

 public class SomeQuartzJob implements Job {

     public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
          InvoiceDAO invoiceDAO = (InvoiceDAO) new InitialContext().lookup("java:global/myApp/myEJB/InvoiceDAO");
          List<Invoice> openInvoices = invoiceDAO.getAllByOpenStatus();
          // verbose exception handling and closing JNDI context omitted for brevity
     }
  }

The @Singleton bean showed earlier was an example of how the Java EE framework calls your code itself at startup. 前面显示的@Singleton bean是一个示例,说明Java EE框架在启动时如何调用代码本身。 For the automatic timer you would use the @Schedule annotation on a bean's method. 对于自动计时器,您可以在bean的方法上使用@Schedule注释。

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

相关问题 应用程序服务器(带有EJB)是Java EE客户端/服务器通信的唯一方法吗? - Are application servers (with EJBs) the only way for Java EE client/server communication? 在Java EE服务器中打包EJB - Packaging EJBs in Java EE server JAVA EE 6在有状态EJB之间共享实例 - JAVA EE 6 share instances between stateful EJBs 在服务器上部署项目Java EE(使用EJB和Servlet) - Deploy project Java EE on server (with EJBs and servlets) 与Java桌面应用程序中的数据库交互的最佳方法 - Best way to interact with database in java desktop application 什么是与JWS Java应用程序的服务器交互的最佳方式 - Whats is the best way to interact with the server of a JWS java application 计算Java EE Web App中用户数的最佳方法 - Best way to count number of users in a Java EE web App 从EJB或Java EE webapp使用http资源的最佳方法 - Best way to consume http resource from EJB or Java EE webapp 在Java EE应用程序中同时进行httpurlconnection调用的最佳方法是什么 - What is the best way to make simultaneous httpurlconnection calls in a Java EE application 从weblogic Java EE应用程序运行Perl脚本的最佳方法 - Best way to run a Perl script from weblogic Java EE application
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM