This article is more than 1 year old

Migrating EJB 2.1 Entity and Session Beans to EJB 3.0

The nuts and bolts

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.

More about

TIP US OFF

Send us news


Other stories you might like