与Java EE中的EJB进行交互的最佳方式 [英] Best way to interact with EJBs in Java EE

查看:188
本文介绍了与Java EE中的EJB进行交互的最佳方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个中等规模的Java EE 6项目,它使用了几个EJB,其中包括通过JPA管理数据库调用的唯一目的。我的问题是什么是添加一个新的类的一些随机的功能的最佳方法,然后调用数据库访问EJB来保存这个类的数据。



如果需要访问注释和注入,这个新类必须是EJB吗?如果它必须与项目的其余部分一起部署,它是否必须是EJB?



我被告知,如果您要添加一个新的逻辑类项目或者必须是EJB,或者您可以使用JNDI远程集成来访问EJB元素并创建某种客户端界面。现在我的新课程只是一个POJO,但不能访问EJB功能。



一般我该怎么办?



编辑:请注意我的问题不是数据库访问。这只是我正在使用的一个例子。我的邀请更广泛。我想知道如何从我创建的其他类访问EJB方法。从一个EJB到另一个EJB,您可以简单地注入其他EJB,因为它们都是容器管理的。但是说我在与EJB相同的包中创建另一个类怎么可能访问这些方法?有可能吗这里最好的做法是什么



现在我有一个类,它从一个URL接收twitter feed数据,然后解析JSON,并返回前10个条目的字符串。我想调用我的管理数据库访问的EJB,并将该字符串传递给其对应的方法,但是我不能这样做,因为我的类不是EJB。

解决方案

EJB通常用于实现任何类型的服务。他们与JPA完美结合,所以经常用于DB访问,但这不是他们唯一的用法。



什么EJB通常适合是建模数据。即他们应该是你的申请中的动词,而不是名词。

  @Stateless 
@Entity
public class CreditCard {//傻,不要这样做!

@Id
长id; + getters / setters
数据到期日; + getter / setters
}

以下更好,这是一个服务,当您的应用程序启动从某个地方获取一些报价数据:

  @Singleton 
@Startup
public class QuoteFetcher {

private List< Quote>报价; // + getter

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

以下是强制性DAO示例:

  @Stateless 
public class JPAInvoiceDAO实现InvoiceDAO {

@PersistenceContext
private EntityManager entityManager ;

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

//更多DAO方法
}

以下显示如何使用声明式安全性,以及bean如何查找外部映射到其私有上下文(ENC)的内容:

  @Stateless 
public class TokenFetcher

@Resource
private SessionContext sessionContext;

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

问题的第二部分似乎是如何在你的代码中使用这些bean。基本上有四种方法:


  1. 在受管Bean中注入

  2. 通过JNDI引导

  3. 在启动时自动调用

  4. 通过计时器自动执行

注入是最简单的方法,但只有托管的bean是注入候选(基本上意味着Java EE框架创建了这个bean,并且你不使用 new()来实例化它)。



例如注入:

  @ManagedBean 
public class InvoiceBacking {

private Long invoiceId; // + getter / setter
私人发票发票; // + getter

@EJB
private InvoiceDAO invoiceDAO;

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

(另见 JSF 2.0#中的通讯处理GET请求参数



通过JNDI引导:

  public class SomeQuartzJob实现Job {

public void execute(JobExecutionContext jobExecutionContext)throws JobExecutionException {
InvoiceDAO invoiceDAO =(InvoiceDAO)new InitialContext()。lookup(java:global / myApp / myEJB / InvoiceDAO);
列表<发票> openInvoices = invoiceDAO.getAllByOpenStatus();
//详细的异常处理和关闭为简洁起见省略了JNDI上下文
}
}

之前展示的@Singleton bean是Java EE框架在启动时调用代码本身的一个例子。对于自动计时器,您可以在bean的方法上使用@Schedule注释。


I have a moderate sized Java EE 6 project that uses several EJBs, including one which sole purpose is managing database calls through 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.

Does this new class have to be an EJB if it needs access to annotations and injections? Does it have to be an EJB if it has to be deployed with the rest of the project?

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. Right now my new class is just a POJO but it's not able to access the EJB functionality.

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. From one EJB to another you can simply inject the other EJB since they're both container managed. But say I create another class in the same package as the EJBs how might How can I access those methods? 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. 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.

解决方案

EJBs are generally used to implement services of any kind. They integrate really well with JPA so are often used for DB access, but that's not their only usage.

What EJBs are typically not suited for is modeling data. I.e. 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:

@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):

@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. There are basically four methods:

  1. Injection in managed beans
  2. Bootstrapping via 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).

E.g. 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)

Bootstrapping via 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. For the automatic timer you would use the @Schedule annotation on a bean's method.

这篇关于与Java EE中的EJB进行交互的最佳方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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