Differences between EJB 3.0 and EJB 2.1

Compared to EJB 2.1, EJB 3.0 simplifies the process of creating Enterprise JavaBean applications.

The underlying concept of the EJB 3.0 specification centers on a plain old Java™ object (POJO) programming model that uses Java annotations to capture information that deployment descriptors used to contain. Deployment descriptors are now optional in most cases. Using default values liberally also means that you need to write and maintain less supporting code. This greatly simplifies the programming experience in creating and using EJB 3.0 components.

While EJB 2.1 added support for Web services, changes in the implementation of session beans, changes in how enterprise beans are invoked and a new XML schema to replace the DTD that defined ejb-jar.xml deployment descriptor, EJB 3.0 has taken this one step further. EJB 3.0 has introduced a lightweight entity bean persistence mechanism through the Java Persistence API. These entities are POJO based and can then be run outside of an EJB container and do not require any interfaces or EJB code in them. Similarly, session beans also no longer require EJB-specific component interfaces either.

Comparison of EJB 2.1 class plus Deployment Descriptor file with equivalent EJB 3.0 class

The examples in Table 1 are functionally equivalent:

Table 1. Comparison of EJB 2.1 and EJB 3.0
EJB 2.1 EJB 3.0

Java Class

public class AccountBean
implements javax.ejb.SessionBean {
 
     SessionContext ctx;
     DataSource accountDB;
 
     public void setSessionContext(SessionContext ctx) {
        this.ctx = ctx;
     }
 
     public void ejbCreate() {
          accountDB = (DataSource)ctx.lookup(
                          "jdbc/accountDB");
 
     }
     public void ejbActivate() { }
     public void ejbPassivate() { }
     public void ejbRemove() { }

     public void setAccountDeposit(int empId,
                                      double deposit) {
       ...
       Connection conn = accountDB.getConnection();
       ...
     }
  ...
}

Java Class

@Stateless
public class AccountBean implements Account
{
     @Resource private DataSource accountDB;
 
     public void setAccountDeposit(int customerId,
                                      double deposit) {
       ...
       Connection conn = accountDB.getConnection();
       ...
     }
  ...
}

Deployment Descriptor

<session>
  <ejb-name>AccountBean</ejb-name>
  <local-home>AccountHome</local-home>
  <local>Account</local>
  <ejb-class>com.example.AccountBean</ejb-class>
  <session-type>Stateless</session-type>
  <transaction-type>Container</transaction-type>
  <resource-ref>
    <res-ref-name>jdbc/accountDB</res-ref-name>
    <res-ref-type>javax.sql.DataSource</res-ref-type>
    <res-auth>Container</res-auth>
  </resource-ref>
</session>
...
<assembly-descriptor>...</assembly-descriptor>
 
The following four facets of Java EE 5 contributed the most to the changes in EJB 3.0 from EJB 2.1: