EJB 3.0 - Development Made Easy
A Look into the Specification using JBoss EJB3.0 Beta
The EJB 3.0 expert committee released a public review of the EJB 3.0 specification on 27th June, 2005. One of the primary goals of the new release is reducing the complexity of EJB architecture from a developer's point of view and to simplify application development. This article explores how EJB 3.0 eases development vis-ΰ-vis earlier releases of the specification, by stepping you through the process of implementing a simple application in EJB 2.1 and EJB 3.0.
Introduction
Enterprise Java Beans (EJB), popular among the J2EE community, is used extensively to develop distributed enterprise applications. Its popularity can be attributed to the fact that EJB helps an application negotiate most of the challenges of a distributed enterprise application, such as resource pooling, transaction management, remote method invocation, and security. Over the years, the EJB specification has undergone a number of revisions, with new features added on at each stage, thereby increasing its complexity. In spite of its immense popularity, EJB has often been accused of being too complex to develop and deploy. With this backdrop, the EJB expert group is now working on EJB 3.0, the next release of the specification. One of the main goals of the new release is to simplify the development and deployment of EJB based applications. The Expert Group released a public review of the specification on 27th June, 2005.
Further, JBoss and Oracle are providing EJB 3.0 preview releases for their application servers. For this article, I implemented a simple application in JBoss Application Server using both EJB2.1 and EJB3.0 (EJB 3.0 Beta 1 from JBoss) to check first hand if EJB3.0 does indeed live up to its promise of making development simpler.
This article would be of interest to Technical Managers, Architects and Developers. Since this paper is on EJB 3.0 specification, an exposure to earlier releases of EJB is desirable.
Problem Areas in Earlier Releases
Before detailing the features of the new specification, here's a brief listing of the various problem areas of the earlier releases of the specification, which makes development complex:
- The EJB 2.x model requires implementation of multiple interfaces in addition to the bean class. To implement a session bean, for example, you'll need to include two interfaces (the business interface and the home interface) and the bean class.
- The current model requires implementation of several unnecessary callback methods (like ejbCreate(), ejbPassivate, and ejbActivate()). So developers include a blank implementation of these callback methods without knowing what they are meant for.
- The deployment descriptor is complex and error prone. It becomes unmanageable in large applications.
- The process of looking up and using EJB is complex, especially from the client side. Besides, the user also needs to have a good knowledge of JNDI to be able to implement EJBs.
- It is mandatory to throw and catch checked exceptions, like CreateException and FinderException, even if they are not functionally required.
In short, the current EJB model has failed to adhere to the J2EE philosophy of "increased productivity through development ease", resulting in a stiff learning curve and preventing wide adoption.
Sample Application
In this article we'll use a simple application and implement it using both EJB2.1 (CMP) and EJB3.0 Beta 1 (from JBoss) in the JBoss application server. The sample application has two entity beans - Department and Employee, with a one-to-many relationship between them. A stateless session bean, Faηade, is used to call the entity beans. See Figure 1.

Figure 1: The Sample Application
Implementing the Demonstration
The first thing to do is to set up the environment. Following are the steps:
1.Download and install the following components:
2.Set up the following environment variables:
- JAVA_HOME (C:\Program Files\Java\jdk1.5.0_01, for example)
- JBOSS_HOME (E:\EJB3_Article\jboss-4.0.2, for example)
- Add Ant to your classpath (C:\Ant-1.6.2\bin, for example)
3.We'll use HSQL database here for the sample application, since it comes inbuilt in the JBoss Application server. Place the hsqldb-ds.xml file in JBOSS HOME\server\all\deploy directory with the following entries:
<?xml version="1.0" encoding="UTF-8"?>
<!-- The Hypersonic embedded database JCA connection factory config
$Id: hsqldb-ds.xml,v 1.15 2004/09/15 14:37:40 loubyansky Exp $ -->
<datasources>
<local-tx-datasource>
<jndi-name>DefaultDS</jndi-name>
<connection-url>jdbc:hsqldb:hsql://localhost:1701</connection-url>
<driver-class>org.hsqldb.jdbcDriver</driver-class>
<user-name>sa</user-name>
<password></password>
<min-pool-size>5</min-pool-size>
<max-pool-size>20</max-pool-size>
<idle-timeout-minutes>0</idle-timeout-minutes>
<track-statements/>
<security-domain>HsqlDbRealm</security-domain>
<metadata>
<type-mapping>Hypersonic SQL</type-mapping>
</metadata>
</local-tx-datasource>
<mbean code="org.jboss.jdbc.HypersonicDatabase" name="jboss:service=Hypersonic">
<attribute name="Port">1701</attribute>
<attribute name="Silent">true</attribute>
<attribute name="Database">default</attribute>
<attribute name="Trace">false</attribute>
<attribute name="No_system_exit">true</attribute>
</mbean>
</datasources>
4.Install EJB 3.0 Beta 1 in JBoss AS 4.0.2. Follow the installation steps provided with EJB 3.0 Beta 1 download. Running the EJB 3.0 Application
Follow these steps to get the EJB 3.0 application up and running:
1.Unzip the file EJB3.0Application.zip in a folder (E:\EJB3_Article, for instance).
2.Go to the command prompt and use the following commands to compile the application:
E:\EJB3_Article\EJB3.0\application> ant compile3.Start JBoss App server. Use run -c all in command prompt at JBOSS_HOME\bin directory.
4.Use the following command in the command prompt to deploy the application:
E:\EJB3_Article\EJB3.0\application> ant deployThis will create a JAR file (EJB3Application.ejb3). Copy this file to the JBOSS_HOME\server\all\deploy directory.
5.Use the following command in the command prompt to run the application:
E:\EJB3_Article\EJB3.0\application> ant run6.Open a browser, go to Hypersonic SQL service http://localhost:8080/jmx-console/HtmlAdaptor?action=inspectMBean&name=jboss%3Aservice%3DHypersonic and click on StartDatabaseManager.
7.The HSQL Database Manager will come up, displaying the database tables DEPARTMENT and EMPLOYEE.
8.If you execute an SQL query on the tables (for example: SELECT * FROM employee), the data from the EMPLOYEE table will be displayed as shown in Figure 2.

Figure 2: HSQL Database Manager
Running the EJB 2.1 Application
Follow these steps to run the EJB 2.1 application:
1.Unzip the file EJB2.1Application.zip in a folder (E:\EJB3_Article, for instance).
2.Update jboss.home in JBOSS_HOME\jboss-build.properties with your folder structure.
3.Go to command prompt and give the following commands to deploy the application:
E:\EJB3_Article\EJB2.1\application> ant -f jboss-build.xml deploy4.Start the JBoss App server.
5.Use the following command to run the application:
E:\EJB3_Article\EJB2.1\application> ant -f jboss-build.xml run-cmp6.Open a browser, go to Hypersonic SQL service http://localhost:8080/jmx-console/HtmlAdaptor?action=inspectMBean&name=jboss%3Aservice%3DHypersonic and click on StartDatabaseManager.
7.The HSQL Database Manager should come up, displaying the database tables DEPARTMENTBEAN and EMPLOYEEBEAN.
8.If you execute an SQL query on the tables, the data will be displayed. EJB 3.0 Features
Next, let's explore the sample EJB 3.0 application and compare the features of the new specification vis-?is the EJB2.1 specification from the perspective of ease of development and deployment. Usage of Plain Java Object and Interfaces
EJB 3.0 makes extensive usage of plain Java objects and interfaces. The Department and Employee entity beans in the sample EJB 3.0 application are plain Java objects. Unlike in earlier releases there is no need to implement local/remote interfaces and home interfaces for entity beans.
Similarly, the FacadeBean stateless session bean is also a Java object. The business interface Fa?eRemote hasn't implemented EJBObject as is required by earlier releases. Annotation @Remote is used to mark it as a remote business interface. Similarly for local interface there is no need to implement EJBLocalObject.
The requirement of home interface is completely done away with. Therefore, none of the beans (both entity and session) in the sample EJB 3.0 application has any home interface. New Persistence Model
The CMP Entity bean in EJB 3.0 uses a lightweight persistence model in line with persistence frameworks like Hibernate (open source) and TopLink (from Oracle). Entity beans are simple POJOs in the new specification and will support features like inheritance and polymorphism.
O/R mapping is defined in the Entity bean class through annotations. For example, @Column is used to map the fields in the EMPLOYEE table to the Employee entity bean in the sample EJB3.0 application.
Entity relationships are also defined through annotations. EJB3.0 supports unidirectional and bi-directional relationships between entity beans, which can be a one-to-one, one-to-many, many-to-one and many-to-many relationship. For example, the one to many relationship between Department and Employee in the sample EJB3.0 application is defined using @OneToMany (in Department) and @ManyToOne (in Employee). Client View of Entity Bean
In EJB 3.0, the entity bean life cycle methods (such as create, remove, and find) are provided by the Entity Manager and not by the Home Interface (as in EJB 2.1). This helps in isolating the client from the JNDI details, since the client doesn't have to look up the home interface before doing any operation on the bean.
Since the EJB 3.0 entity beans are POJOs, they can be instantiated using the new operator, and the instance variable of the entity can be set using setter methods. But the EntityManager API needs to be used to save or retrieve data from the database. The EntityManager object can be injected using @PersistenceContext annotation.
In the sample EJB 3 application, the following code is used in FacadeBean to create the entity Department:
@PersistenceContextTo create the same Department entity in EJB 2.1, we have to make the following entry in the deployment descriptor, in the sample application:
private EntityManager manager;
.
Department department = new Department();
department.setName(deptName);
manager.persist(department);
<ejb-local-ref>In the FacadeBean, make a JNDI lookup for the LocalDepartmentHome, like this:
<ejb-ref-name>ejb/Department</ejb-ref-name>
<ejb-ref-type>Entity</ejb-ref-type>
<local-home>com.infosys.EJB2.application.LocalDepartmentHome</local-home>
<local>com.infosys.EJB2.application.LocalDepartment</local>
<ejb-link>DepartmentBean</ejb-link>
</ejb-local-ref>
private LocalDepartmentHome lookupDepartment() throws NamingExceptionIn the home interface (LocalDepartmentHome) the 'create' method is called to get the local interface (LocalDepartment):
{
Context initial = new InitialContext();
Object objref = initial.lookup("java:comp/env/ejb/Department");
return (LocalDepartmentHome) objref;
}
LocalDepartment department = departmentHome.create(deptID,deptName);Thus, the client view of the Entity bean in EJB3.0 specification is much simplified.
Metadata Annotations replaces Deployment Descriptors
EJB 3.0 uses metadata annotations instead of deployment descriptors. While deployment descriptors are XML based, verbose and error prone, annotation is a simpler and more elegant approach to annotate Java code from within the code itself.
Annotation is a special kind of Java construct introduced in JDK 1.5 to decorate a class, method, field or variable. The EJB 3.0 specification has defined a set of annotations like bean type, type of interface, transaction attributes, and security. These annotations can be set in the bean class itself instead of adding these details in a separate XML file.
For example, stateless session bean is defined in the sample EJB3.0 application as:To implement the same stateless session bean in sample EJB2.1 application, we would have to make the following entries in the ejb-jar.xml deployment descriptor:
/* Session bean class */
@Stateless
public class FacadeBean implements FacadeRemote
{
..
}
/* Remote business interface */
@Remote
public interface FacadeRemote
{
.
}
<session>That said, deployment descriptors are supported in EJB 3.0 to provide backward compatibility to earlier versions of EJB. Life Cycle Methods made Optional
<ejb-name>FacadeBean</ejb-name>
<home>com.infosys.EJB2.application.FacadeHome</home>
<remote>com.infosys.EJB2.application.Facade</remote>
<ejb-class>com.infosys.EJB2.application.FacadeBean</ejb-class>
<session-type>Stateless</session-type>
.
</session>
In EJB 2.1 (and earlier releases) it is mandatory to provide the implementation of several life cycle methods in the Bean class for both Entity and Session beans. In most cases there is no functional requirement for them, so you end up providing blank implementations just to meet the specification requirement. For example, in the sample EJB 2.1 application, I had to provide a blank implementation of ejbLoad(), ejbStore(), ejbPassivate(), ejbActivate(), ejbRemove() methods in the EmployeeBean class.
To mitigate this problem, the EJB 3.0 specification has made the implementation of life cycle methods optional. This makes the code simpler, increases readability, and reduces code size. For example, in the sample EJB 3.0 application, the Department bean does not have any life cycle implementation since there is no functional requirement.
The specification instead provides a number of annotations that can be used to mark any method as a callback method. In case of the Entity bean we can use @PrePersist, @PostPersist, @ PreRemove, and @PostRemove. Similar annotations are defined for Session beans as well. Once any method is annotated with any of these, the container automatically calls the methods at different stages of the bean life cycle.
For example, in the sample EJB3.0 application, the Employee bean has a method samplePostPersist() annotated with @PostPersist. The samplePostPersist() method will be called after the employee entity is created in the database:
@PostPersistFurther, you can also move the implementations of the callback method into a separate class, to prevent the bean class from getting cluttered. Then that class can be specified in the bean using either @EntityListener (for entity bean) or @CallbackListener (for session bean). Checked Exception
public void samplePostPersist()
{
System.out.println("Added Employee having name = "+ this.getName() +" and Age = "+ this.getAge());
}
In EJB 3.0, it is not mandatory to handle checked exceptions like CreateException and FinderException. An application can however declare its own application exceptions and include them in the 'throws clause' of bean methods.
For system exceptions, the container throws a javax.ejb.EJBException. However, the bean methods do not have to catch these exceptions. Primary Key Generation
In earlier releases, the generation of primary key for entity beans was left to the application developers. For example, in the sample EJB 2.1 application I passed a primary key while creating Employee and Department entities (the primary key is hard coded in the sample for simplicity). Several approaches like sequence block pattern, UUID generators can be used, but requires extra effort and time for coding, testing.
EJB 3.0 has addressed this issue with Id annotation. Depending upon the application requirement Id annotation can be used with different primary key generation strategies defined by GeneratorType enum. TABLE, SEQUENCE, IDENTITY, AUTO, NONE are the available GeneratorTypes.
In the sample EJB3.0 application, the Department and Employee entity beans use Id with AUTO and IDENTITY GeneratorTypes respectively. Number of Artifacts
The number of artifacts (Java and XML files) required in EJB 3.0 is considerably less. The only artifact that needs to be implemented in the Entity bean is the entity class, since Home and Business interfaces are not required. In case of session bean, the home interface is not required. Even the business interface is optional; the container will generate it, if hasn't been provided. Moreover, no deployment descriptor is required as the details are included in the code itself.
The sample EJB 3.0 application with two entity beans (Employee and Department) and one stateless session bean (Faηade) required four files (one bean class for each entity bean, one bean class for the session bean, and one remote interface for session bean). With EJB 2.1, 10 files were required to implement the two entity beans (one bean class and two interfaces for each of Department/Employee/Fa?e bean and one XML deployment descriptor). As you can see, in a real life application wherein large number of beans is required, using EJB 3.0 will significantly reduce the number of artifacts resulting in better maintainability. Summary
In this article, we have explored the features provided by EJB 3.0 specification to simplify the development and deployment of entity and session beans. As is evident from the sample application features like usage of plain Java objects and interfaces, annotations and the new persistence model for entity bean will make development of EJB much simpler and less verbose. Additionally, features like EntityManager API and primary key generation are a big plus. About the Author
Brijesh Deb has a M.S in Software Systems. He works as a Technical Architect with the Software Engineering and Technology Labs of Infosys Technologies Limited, at Bangalore (India). Resources & References
- JDK 1.5 API docs
- JBoss EJB 3.0
- JSR 220: Enterprise JavaBeans 3.0
- EJB 3.0 resources from Oracle
- Code Download for the sample EJB3.0 application
- Code Download for the sample EJB2.1 application
Feedback on this article can be mailed to editors@jaxmag.com.



