Migrating EJB 2.1 Entity and Session Beans to EJB 3.0
The nuts and bolts
Posted in Developer, 25th April 2006 06:02 GMT
Free whitepaper – Ensuring high service levels in cloud computing
Listing 2. CatalogBean.java EJB 3.0 Session Bean
@Stateless
@Local ({CatalogLocal.java})
public class CatalogBean implements CatalogLocal {
public String getJournal(String publisher) {
if (publisher.equals("Oracle Publisher"))
return new String("Oracle Magazine");
if (journal.equals("OReilly"))
return new String("dev2dev");
}
}
In EJB 3.0, the component and home interfaces of EJB 2.1 are replaced with a business interface. The business interfaces for the session bean are POJIs, and do not extend the EJBLocalObject or the EJBObject. A local business interface is denoted with the annotation @Local. A remote business interface is denoted with the annotation @Remote. A remote business interface does not throw the RemoteException. The local business interface corresponding to the session bean class is listed in Listing 3.
Listing 3. CatalogLocal.java. Local Interface of Session Bean
@Local
public interface CatalogLocal{
public String getJournal(String publisher);
}
A client for an EJB 2.1 session bean gets a reference to the session bean with JNDI. The JNDI name for the CatalogBean session bean is CatalogLocalHome. The local/remote object is obtained with the create() method. The client class for the EJB 2.1 session bean is listed in Listing 4.
Listing 4. EJB 2.1 Session Bean Client Class
import javax.naming.InitialContext;
public class CatalogClient {
public static void main(String[] argv) {
try {
InitialContext ctx=new InitialContext();
Object objref=ctx.lookup("CatalogLocalHome");
CatalogLocalHome catalogLocalHome=(CatalogLocalHome)objref;
CatalogLocal catalogLocal=(CatalogLocal)catalogLocalHome.create();
String publisher="OReilly";
String journal=catalogLocal.getJournal(publisher);
System.out.println("Journal for Publisher: "+publisher +" "+journal);
}
catch (Exception e) {}
}
}
In EJB 3.0 a reference to a resource is obtained with dependency injection with the @Inject annotation or the @Resource annotation. JNDI lookup and create() method invocation is not required in EJB 3.0. The client class for the EJB 3.0 session bean is listed in Listing 5.
Next page: Listing 5. EJB 3.0 Session Bean Client Class

Analyst Keynote: The Register Agile Data Center Summit
Market Primer: ERP Systems
Enabling The Agile Data Center
10 Strategies for Choosing a Midmarket ERP Solution
Office 2010 fights Google with SharePoint bloat
Ubuntu's Karmic Koala bares fangs at Windows 7
Change your views: OS X tags exploited
Microsoft 'Dallas' muscles Google data crusade