Original URL: https://www.theregister.com/2006/04/25/ejb3_migration/

Migrating EJB 2.1 Entity and Session Beans to EJB 3.0

The nuts and bolts

By Deepak Vohra

Posted in Software, 25th April 2006 06:02 GMT

In this tutorial, migration of EJB 2.1 specification EJBs to EJB 3.0 specification is discussed. EJB 3.0 Session and Entity beans require JDK 5.0 as metadata annotations are used in the specification.

The EJB 2.1 specification is implemented in the javax.ejb package classes and interfaces. A session bean is required to implement the SessionBean interface.

An EJB 3.0 session bean class is a POJO (Plain Old Java Object – Martin Fowler) and does not implement the SessionBean interface.

An EJB 2.1 session bean class includes one or more ejbCreate methods, the callback methods ejbActivate, ejbPassivate, ejbRemove, and setSessionContext, and the business methods defined in the local/remote interface.

An EJB 3.0 session bean class includes only the business methods.

A home interface in an EJB 2.1 session EJB extends the javax.ejb.EJBHome interface; a local home interface extends the javax.ejb.EJBLocalHome interface. A remote interface in an EJB 2.1 Session EJB extends the javax.ejb.EJBObject interface; a local interface extends the javax.ejb.EJBLocalObject interface. In EJB 3.0 the home/local home and remote/local interfaces are not required. The EJB interfaces are replaced with a POJI (Plain Old Java Interface) business interface. If a business interface is not included with the session bean class, a POJI business interface gets generated from the session bean class by the EJB server.

An EJB 2.1 session EJB includes a deployment descriptor that specifies the EJB name, the bean class name, and the interfaces. The deployment descriptor also specifies the bean type of Stateless/Stateful. In EJB 3.0 a deployment descriptor is not required for a session bean.

An EJB 2.1 Entity EJB bean class implements the EntityBean class and the callback methods in the interface. An EJB 2.1 entity bean also includes the ejbCreate and ejbPostCreate methods, which are not required in the EJB 3.0 specification. An entity bean includes the component and home interfaces that extend the EJBObject/EJBLocalObject and EJBHome/EJBLocalHome interfaces.

In comparison, an EJB 3.0 entity bean class is a POJO which does not implement the EntityBean class. The callback methods, the ejbCreate and ejbPostCreate methods are not required in the EJB 3.0 entity bean class. Also, the component and home interfaces and deployment descriptors are not required in EJB 3.0.

The values specified in the EJB 2.1 deployment descriptor are included in EJB 3.0 bean class with JDK 5.0 annotations.

Thus, the number of classes/interfaces/deployment descriptors is reduced in the EJB 3.0 specification. In this tutorial we shall migrate an example Session EJB and an example Entity EJB from EJB 2.1 to EJB 3.0 specification.

Introduction

The purpose of the Enterprise JavaBeans EJB 3.0 specification is to improve the EJB architecture by reducing its complexity from the developer's point of view.

EJB 3.0 is implemented by different application servers such as those from JBoss, Oracle and Caucho.

The implementation in the different application servers may vary. In this tutorial an example session bean and an example entity bean are migrated from EJB 2.1 to EJB 3.0 specification. Migration from EJB 2.0 is similar.

Migrating a Session Bean

In this section we shall migrate an example stateless session bean from EJB 2.1 specification to EJB 3.0 specification. The session bean class implements the SessionBean interface. The session bean class has a ejbCreatemethod, a business method, getJournal(), and the callback methods. The example session bean class CatalogBean.java is listed in Listing 1.

Listing 1. CatalogBean.java EJB 2.1 Session Bean

import javax.ejb.SessionBean;
import javax.ejb.SessionContext;

public class CatalogBean implements SessionBean{
   private SessionContext ctx;

   public String getJournal(String publisher){
      if (publisher.equals("Oracle Publisher"))
         return new String("Oracle Magazine");
      if (journal.equals("OReilly"))
         return new String("dev2dev");
   }

   public void ejbCreate(){}
   public void ejbRemove() {}
   public void ejbActivate() {}
   public void ejbPassivate() {}
   public void setSessionContext(SessionContext ctx) {this.ctx=ctx;}
}

In EJB 3.0, metadata annotations are used to specify the session bean type and local and remote business interfaces. A stateless session bean is specified with annotation @Stateless, a stateful session bean with annotation @Stateful. Component and home interfaces are not required for a session bean. A session bean is required to implement a business interface. The business interface, which is a POJI, may be a local or remote interface. A local interface is denoted with annotation @Local and a remote interface is denoted with annotation @Remote. A session bean may implement one or both (local and remote) of the interfaces. If none of the interfaces is specified, a local business interface gets generated. The remote and local business interface class may be specified in the @Local and @Remote annotations. For example, a local business interface may be specified as, @Local ({CatalogLocal.class})

The EJB 3.0 session bean corresponding to the EJB 2.1 stateless session bean is annotated with the metadata annotation @Stateless. The EJB 3.0 bean class does not implement the SessionBean interface. The EJB 3.0 session bean implements a business interface. The @Local annotation specifies the local business interface for the session bean. The EJB 3.0 session bean corresponding to the EJB 2.1 example session bean is listed in Listing 2.

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.

Listing 5. EJB 3.0 Session Bean Client Class

public class CatalogClient {
    @Inject CatalogBean;
    CatalogBean catalogBean;

    String publisher="OReilly";
    String journal=catalogBean.getJournal(publisher);
    System.out.println("Journal for Publisher: "+publisher +" "+journal);
}

Migrating an Entity Bean

In this section, we shall migrate an EJB 2.1 entity bean to the EJB 3.0 specification. An EJB 2.1 entity bean implements the EntityBean interface. An entity bean consists of getter/setter CMP (container managed persistence) field methods, getter/setter CMR (container managed relationships) field methods, callback methods and ejbCreate/ejbPostCreate methods. The example entity bean, CatalogBean.java, that will be migrated to EJB 3.0, includes a local component interface, CatalogLocal.java, a local home interface, catalogLocalHome.java and the ejb-jar.xml deployment descriptor. The EJB 2.1 entity bean is listed in Listing 6.

Listing 6. CatalogBean.java. EJB 2.1 Entity Bean

import javax.ejb.EntityBean;
import javax.ejb.EntityContext;

public class CatalogBean implements EntityBean {
    private EntityContext ctx;

    public abstract void setCatalogId();
    public abstract String getCatalogId();

    public abstract void setJournal();
    public abstract String getJournal();

    public abstract void setPublisher();
    public abstract String getPublisher();

    public abstract void setEditions(java.util.Collection editions);

    public abstract java.util.Collection getEditions();

    public String ejbCreate(String catalogId) {
        setCatalogId(catalogId);
        return null;
    }

    public void ejbRemove() {}
    public void ejbActivate() {}
    public void ejbPassivate() {}
    public void ejbLoad() {}
    public void ejbStore() {}

    public void setEntityContext(EntityContext ctx) {
        this.ctx=ctx;
    }

    public void unsetEntityContext() {
        ctx = null;
    }
}

The ejb-jar.xml deployment descriptor specifies the EJB classes/interfaces, CMP fields, EJB QL queries, and CMR relationships. The CatalogBean entity bean includes a finder method, findByJournal; and a CMR relationship with another entity bean, Edition. The ejb-jar.xml for the CatalogBean EJB is listed in Listing 7.

Listing 7. ejb-jar.xml

<?xml version="1.0"?>
<!DOCTYPE ejb-jar PUBLIC
"-//Sun Microsystems, Inc.//DTD Enterprise JavaBeans 2.0//EN"
"http://java.sun.com/dtd/ejb-jar_2_0.dtd">
<ejb-jar>
  <enterprise-beans>
    <entity>
    <ejb-name>Catalog</ejb-name>
    <local-home>CatalogLocalHome</local-home>
    <local>CatalogLocal</local>
    <ejb-class>CatalogBean</ejb-class>
    <persistence-type>Container</persistence-type>
    <prim-key-class>String</prim-key-class>
    <reentrant>False</reentrant>
      <cmp-version>2.x</cmp-version>
      <abstract-schema-name>Catalog</abstract-schema-name>
      <cmp-field>
        <field-name>catalogId</field-name>
      </cmp-field>
      <cmp-field>
        <field-name>journal</field-name>
      </cmp-field>
      <cmp-field>
        <field-name>publisher</field-name>
      </cmp-field>
        <query>
         <query-method>
           <method-name>findByJournal</method-name>
           <method-params>
            <method-param>java.lang.String</method-param>
           </method-params>
         </query-method>
         <ejb-ql>
           <![CDATA[SELECT DISTINCT OBJECT(obj)  FROM Catalog obj WHERE obj.journal = ?1 ]]>
         </ejb-ql>
       </query>
      </entity>
    </enterprise-beans>
    <relationships>

    <ejb-relation>
      <ejb-relation-name>Catalog-Editions</ejb-relation-name>
      <ejb-relationship-role>
        <ejb-relationship-role-name>
          Catalog-Has-Editions
        </ejb-relationship-role-name>
        <multiplicity>One</multiplicity>
        <relationship-role-source>
          <ejb-name>Catalog</ejb-name>
        </relationship-role-source>
        <cmr-field>
          <cmr-field-name>editions</cmr-field-name>
          <cmr-field-type>java.util.Collection</cmr-field-type>
        </cmr-field>
      </ejb-relationship-role>
      <ejb-relationship-role>
        <ejb-relationship-role-name>
          Editions-Belong-To-Catalog
        </ejb-relationship-role-name>
        <multiplicity>One</multiplicity>
        <cascade-delete />
        <relationship-role-source>
          <ejb-name>Edition</ejb-name>
        </relationship-role-source>
      </ejb-relationship-role>
    </ejb-relation>
  </relationships>
</ejb-jar>

An EJB 3.0 entity bean class is a POJO and does not implement the EntityBean interface. In an EJB 3.0 entity bean, the local interface, the local home interface, and the deployment descriptors are not required. Only a bean class annotated with the metadata annotation @Entity is required. The finder methods specified in EJB 2.0 deployment descriptor ejb-jar.xml, with the <query/> elements, are included in the EJB 3.0 bean class with the @NamedQuery annotation. The CMR relationships specified in ejb-jar.xml with <ejb-relation/> elements are included in the EJB 3.0 bean class with metadata annotations. The primary key field in EJB 3.0 is specified with the annotation @Id. Some of the EJB 3.0 metadata annotations are listed in Table 1.

Table 1. EJB 3.0 Metadata Annotations

Annotation Description Annotation Elements
@Entity Specifies an entity bean.
@Table Specifies the entity bean table. name, schema
@Id Specifies an identifier property.
@Column Specifies the database table column for a persistent entity bean property. name, primaryKey, nullable, length
@NamedQueries Specifies a group of named queries.
@NamedQuery Specifies a named query or a query associated with a finder method. name, queryString
@OneToMany Specifies a one-to-many CMR relationship. cascade
@OneToOne Specifies a one-to-one CMR relationship. cascade
@ManyToMany Specifies a many-to-many CMR relationship. cascade
@ManyToOne Specifies a many-to-one CMR relationship. cascade

The EJB 3.0 annotation types are defined in the javax.persistence package. The EJB 3.0 entity bean class, corresponding to the EJB 2.1 entity bean class, is annotated with metadata annotation @Entity. The finder method findByJournal in the EJB 2.1 bean class is specified in the EJB 3.0 POJO class with the @NamedQuery annotation. The CMR relationship Catalog-Editions in the EJB 2.1 entity bean is specified in EJB 3.0 entity bean class with the @OneToMany annotation. The @Id annotation specifies the identifier property catalogId. The @Column annotation specifies the database column corresponding to the identifier property catalogId. If a @Column annotation is not specified for a persistent entity bean property, the column name is same as the entity bean property name. Transient entity bean properties are specified with the @Transient annotation. The EJB 3.0 entity bean POJO class, corresponding to the EJB 2.1 entity bean is listed in Listing 8.

Listing 8. CatalogBean.java. EJB 3.0 Entity Bean POJO Class

import javax.persistence.Entity;
import javax.persistence.NamedQuery;
import javax.persistence.Id;
import javax.persistence.Column;
import javax.persistence.OneToMany;

@Entity
@NamedQuery(name="findByJournal",
    queryString="SELECT DISTINCT OBJECT(obj)  FROM Catalog obj WHERE obj.journal = ?1")

public class CatalogBean{
    public CatalogBean() {}
    public CatalogBean(String catalogId) {
        this.catalogId=catalogId;
    }

    private String catalogId;
    private String journal;
    private String publisher;

    @Id
    @Column(name="CatalogId", primaryKey="true")
    public  String getCatalogId() {return catalogId;}
    public  void setCatalogId() {this.catalogId=catalogId;}

    public  void setJournal(String journal) {this.journal=journal;}
    public String getJournal() {return journal;}

    public  void setPublisher(String publisher) {this.publisher=publisher;}
    public  String getPublisher() {return publisher;}

    private java.util.Collection<Edition> editions;

    @OneToMany
    public  void setEditions(java.util.Collection editions) {
        this.editions=editions;
    }

    public  java.util.Collection getEditions() {return editions;}
}

An EJB 2.1 entity bean is created with the create() method in the entity bean home/local home interface. A client for an EJB 2.1 entity bean obtains a reference for the entity bean with JNDI lookup. An example code snippet to create an instance of the example EJB 2.1 entity bean is:

InitialContext ctx=new InitialContext();
Object objref=ctx.lookup("CatalogLocalHome");
CatalogLocalHome catalogLocalHome=(CatalogLocalHome)objref;

//Create an instance of Entity bean
CatalogLocal catalogLocal=(CatalogLocal)catalogLocalHome.create(catalogId);

The example client class for the EJB 2.1 entity bean class is available in the resources zip file . CatalogLocalHome is the JNDI name of the CatalogBean entity bean.

To access the getter/setter methods of an entity bean, the remote/local object in EJB 2.1 is obtained with the finder methods:

CatalogLocal catalogLocal =
    (CatalogLocal) catalogLocalHome.findByPrimaryKey(catalogId);

A entity bean instance is removed with the remove() method:

catalogLocal.remove();

The example client class for the EJB 2.1 entity bean class is available in the resources zip file.

An EJB 3.0 entity bean class does not include the local/remote and home/local home interfaces. In EJB 3.0, persistence and lookup is provided by the EntityMangerclass.

Some of the methods in the javax.persistence.EntityManager class are listed in Table 2.

Table 2. EntityManager Class

EntityManager Method Description
persist Creates an entity bean instance.
createNamedQuery Creates a named query.
find Finds an entity bean instance.
createQuery Creates an EJBQL query.
remove Removes an entity bean instance.

In a session bean client class for EJB 3.0 entity bean, the EntityManager reference is obtained with the @Resource annotation:

@Resource
private EntityManager em;

An entity bean instance is created with the persist() method of the EntityManager class:

CatalogBean catalogBean=new CatalogBean(catalogId);
em.persist(catalogBean);

An entity bean instance is obtained with the find() method:

CatalogBean catalogBean=(CatalogBean)em.find("CatalogBean", catalogId);

A finder method may be defined corresponding to the named query findByJournal in the entity bean POJO class. In the finder method a Query object is obtained with the createNamedQuery method:

Query query=em.createNamedQuery("findByJournal");

Set the Query object parameters with the setParameter method:

query.setParameter(0, journal);

Obtain a Collection of the CatalogBean with the getResultList() method. If a Query object returns a single result, the getSingleResult() is used:

java.util.Collection catalogBeanCollection=(CatalogBean)query.getResultList();

An entity bean instance is removed with the remove() method of the EntityManager class:

CatalogBean catalogBean;
em.remove(catalogBean);

The client class for the EJB 3.0 entity bean is listed in Listing 9.

Listing 9. CatalogClient. EJB 3.0 Client Class

import javax.ejb.Stateless;
import javax.ejb.Resource;
import javax.persistence.EntityManager;
import javax.persistence.Query;

@Stateless
@Local
public class CatalogClient implements CatalogLocal {
    @Resource
    private EntityManager em;

    public void create(String catalogId) {
        CatalogBean catalogBean=new CatalogBean(catalogId);
        em.persist(catalogBean);
    }

    public CatalogBean findByPrimaryKey(String catalogId) {
        return (CatalogBean)em.find("CatalogBean", catalogId);
    }

    public java.util.Collection findByJournal(String journal) {
        Query query=em.createNamedQuery("findByJournal");
        query.setParameter(0, journal);
        return (CatalogBean)query.getResultList();
    }

    public void remove(CatalogBean catalogBean) {
        em.remove(catalogBean);
    }
}

Summary

So, to summarise this tutorial:

Deepak Vohra is a Sun Certified Java Programmer and Sun Certified Web Component Developer. Deepak is a Web developer; and has published in XML Journal, WebLogic Developer's Journal and ONJava.com.