- Background
- Prerequisites
- Session Bean Components
- Summary
- What's Next?
- Links
Session Bean Components
A session bean is composed of the following components:
-
Remote interface
-
Home interface
-
Bean class
The remote interface defines the business methods of the session bean; these are the action methods that operate on the database data.
The home interface is used to create and locate session beans. For a stateless session bean, we'll only be interested in creating a default bean (remember that stateless session beans cannot persist data between method calls).
The Bean class implements all of the methods defined in the remote interface.
In this example, I want to create a database manager session bean that is our front end to a database; it contains methods to manipulate two tables: user and company. The tables are very simple (see Tables 1 and 2). The model is simply that a user can belong to a single company and a company can contain multiple users.
Table 1
Company Table
Field |
Description |
Data Type |
id |
Company ID (primary key) |
NUMBER |
name |
Company name |
VARCHAR |
Table 2
User Table
Field |
Description |
Data Type |
id |
User ID (primary key) |
NUMBER |
name |
Username |
VARCHAR |
company |
User's company (primary key) |
NUMBER |
The session bean also makes use of two helper classes; these are standard classes that represent a company and a user: com.informit.javasolutions.database.CompanyInfo and com.informit.javasolutions.database.UserInfo, respectively.
Remote Interface
The remote interface defines the session bean's business methods. We're going to define the following functionality:
-
Add a user
-
Remove a user
-
Find a user
-
Add a company
-
Remove a company
-
Find a company
-
Find all companies
-
Find all users who work for a specific company
-
Retrieve the number of users in the database
-
Retrieve the number of users who work for a specific company in the database
Listing 1 shows the source code for the DatabaseManager remote interface.
Listing 1 DatabaseManager Remote Interface (DatabaseManager.java)
package com.informit.javasolutions.databasemanager; // Import the EJB classes import java.rmi.RemoteException; import javax.ejb.FinderException; import javax.ejb.EJBObject; // Import our database objects import com.informit.javasolutions.database.CompanyInfo; import com.informit.javasolutions.database.UserInfo; /** * The session bean that manages all transactions with the * User Entity Bean */ public interface DatabaseManager extends EJBObject { /** * Adds a new User to the Database */ public abstract void addUser( UserInfo user ) throws RemoteException; /** * Removes the specified User from the Database */ public abstract void removeUser( int id ) throws RemoteException; /** * Finds a User by its id */ public abstract UserInfo findUser( int id ) throws RemoteException; /** * Adds a new Company to the Database */ public abstract void addCompany( CompanyInfo company ) throws RemoteException; /** * Removes the specified Company from the Database */ public abstract void removeCompany( int id ) throws RemoteException; /** * Finds a Company by its id */ public abstract CompanyInfo findCompany( int id ) throws RemoteException; /** * Returns all companies in the database */ public abstract CompanyInfo[] findCompanies() throws RemoteException; /** * Returns all the users that belong to the specified company */ public abstract UserInfo[] findUsersForCompany( int id ) throws RemoteException; /** * Returns the number of Users in the database */ public abstract int getNumberOfUsers() throws RemoteException; /** * Returns the number of Users for a * specific company in the database */ public abstract int getNumberOfUsers( int company ) throws RemoteException; }
Listing 1 starts by importing the EJB classes and the database classes. Next it declares the com.informit.javasolutions.databasemanager.DatabaseManager interface; this, like all EJB remote interfaces, must extend the javax.ejb.EJBObject interface.
The methods of the DatabaseManager interface offer the aforementioned functionality and interact with the database table helper classes: CompanyInfo and UserInfo. All methods must declare that they can throw java.rmi.RemoteException; this is inherited from EJB's RMI roots.
Home Interface
The home interface defines the methods that will create and locate a session bean; we'll only be concerned with a default create method. Listing 2 shows the complete source code for the DatabaseManager home interface.
Listing 2 DatabaseManager Home Interface (DatabaseManagerHome.java)
package com.informit.javasolutions.databasemanager; // Import the EJB classes import java.rmi.RemoteException; import javax.ejb.*; /** * The Home interface for the DatabaseManager session bean */ public interface DatabaseManagerHome extends EJBHome { /** * Creates an instance of the DatabaseManager object */ public DatabaseManager create() throws RemoteException, CreateException; }
Listing 2 first imports the EJB classes. Next it declares the com.informit.javasolutions.databasemanager.DatabaseManagerHome interface; this, like all EJB home interfaces, must extend the javax.ejb.EJBHome interface.
The only method in this interface is the default create() method; this method declares that it can throw the java.rmi.RemoteException if an network error occurs and that it can throw the javax.ejb.CreateException if the EJB container cannot create an instance of the bean. Finally, it returns an instance of a class implementing the bean's remote interface.
Bean Class
The Bean class implements the business methods defined in the remote interface. Listing 3 shows a partial implementation of the com.informit.javasolutions.databasemanager.DatabaseManagerBean class; please refer to the source code.
Listing 3 DatabaseManager Bean Class (DatabaseManagerHome.java)
package com.informit.javasolutions.databasemanager; // Import the JNDI classes import javax.naming.*; import javax.rmi.PortableRemoteObject; // Import the EJB classes import java.rmi.RemoteException; import javax.ejb.*; // Import the Helper classes import com.informit.javasolutions.database.UserInfo; import com.informit.javasolutions.database.CompanyInfo; // Import the collection classes import java.util.*; // Import the SQL classes import javax.sql.*; import java.sql.*; /** * Manages access to the Database */ public class DatabaseManagerBean implements SessionBean { /** * Adds a new User to the Database */ public void addUser( UserInfo user ) { ... } /** * Removes the specified User from the Database */ public void removeUser( int id ) { ... } /** * Finds a User by its id */ public UserInfo findUser( int id ) { ... } /** * Adds a new Company to the Database */ public void addCompany( CompanyInfo company ) { ... } /** * Removes the specified Company from the Database */ public void removeCompany( int id ) { ... } /** * Finds a Company by its id */ public CompanyInfo findCompany( int id ) { ... } /** * Returns all companies in the database */ public CompanyInfo[] findCompanies() { ... } /** * Returns all the users that belong to the specified company */ public UserInfo[] findUsersForCompany( int company ) { ... } /** * Returns the number of Users in the Database */ public int getNumberOfUsers() { ... } /** * Returns the number of Users in the ConfigServer */ public int getNumberOfUsers( int company ) { ... } /** * Returns a connection to the ConfigServer Database */ private Connection getConnection() throws SQLException { try { // Get a JNDI Context Context jndiContext = new InitialContext(); // Get a datasource for the ConfigServerDB DataSource ds = ( DataSource ) jndiContext.lookup( "java:comp/env/jdbc/InformIT" ); // Return a connection to the database return ds.getConnection(); } catch( NamingException eNaming ) { throw new EJBException( eNaming ); } } public void ejbCreate() {} public void ejbRemove() {} public void ejbActivate() {} public void ejbPassivate() {} public void setSessionContext( SessionContext ctx ) {} }
The DatabaseManagerBean class imports the EJB classes, the JNDI classes, the SQL classes, the collection classes, and the helper classes. Like all session beans, the DatabaseManagerBean class implements the javax.ejb.SessionBean interface. Table 3 shows the methods defined in the javax.ejb.SessionBean interface; we must provide implementations of these methods in the DatabaseManagerBean class (see the end of Listing 3).
Table 3
javax.ejb.SessionBean Interface Methods
Method |
Description |
ejbActivate() |
The activate method is called when the instance is activated from its "passive" state. |
ejbPassivate() |
The passivate method is called before the instance enters the "passive" state. |
ejbRemove() |
A container invokes this method before it ends the life of the session object. |
setSessionContext(SessionContext ctx) |
This sets the associated session context. |
The business methods are implemented very similarly to the addUser() method shown in Listing 4.
Listing 4 DatabaseManagerBean's addUser() method
/** * Adds a new User to the Database */ public void addUser( UserInfo user ) { Connection conn = null; PreparedStatement statement = null; try { String insert = "INSERT INTO users VALUES (?, ?, ?)"; conn = getConnection(); statement = conn.prepareStatement( insert ); statement.setInt( 1, user.getId() ); statement.setString( 2, user.getName() ); statement.setInt( 3, user.getCompany() ); int rows = statement.executeUpdate(); if( rows != 1 ) { throw new EJBException( "Unable to insert user: " + user.getName() ); } } catch( SQLException e ) { e.printStackTrace(); throw new EJBException( e ); } finally { try { if( statement != null ) statement.close(); if( conn != null ) conn.close(); } catch( SQLException e ) { e.printStackTrace(); } } }
The addUser() method first declares its database resources, and then builds a JDBC java.sql.PreparedStatement class with an SQL query (update in this case) and executes it. If a database error occurs, the method throws a javax.ejb.EJBException containing the java.sql.SQLException object. The finally block cleans up all of the database resources.
The last method defined in the DatabaseManagerBean class is the getConnection() method. The getConnection() method gets a reference to the JNDI server and then looks up a database connection:
DataSource ds = ( DataSource ) jndiContext.lookup( "java:comp/env/jdbc/InformIT" );
The name "java:comp/env/jdbc/InformIT" is going to refer to the SQLServerPool that we created earlier; the name will be resolved in the bean's deployment descriptor.
The javax.sql.DataSource interface is the programmatic interface to retrieving a database connection from a JNDI database connection pool. Once the database connection pool has been created, we can simply call the getConnection() method to get a java.sql.Connection. Table 4 shows the methods defined in the DataSource interface.
Table 4
javax.sql.DataSource Interface Methods
Method |
Description |
Connection getConnection() |
Attempts to establish a database connection. |
Connection getConnection(String username, String password) |
Attempts to establish a database connection. |
int getLoginTimeout() |
Gets the maximum time in seconds that this data source can wait while attempting to connect to a database. |
java.io.PrintWriter getLogWriter() |
Gets the log writer for this data source. |
void setLoginTimeout(int seconds) |
Sets the maximum time in seconds that this data source will wait while attempting to connect to a database. |
void setLogWriter(java.io.PrintWriter out) |
Sets the log writer for this data source. |
ejbActivate() |
The activate method is called when the instance is activated from its "passive" state. |
The JDBC driver that you use to access your database will implement the DataSource interface and provide implementations for each of its methods.
Compiling
Place all three of these files in the following package:
com.infomit.javasolutions.databasemanager
Place the CompanyInfo and UserInfo classes in the following package:
com.infomit.javasolutions.database
Recall that the directory structure mimics the package:
com/infomit/javasolutions/database com/infomit/javasolutions/databasemanager
Using the JDK 1.3, compile these five files with the following files added to your CLASSPATH:
YOUR_JBOSS_HOME/lib/ext/ejb.jar YOUR_JBOSS_HOME/lib/jdbc2_0-stdext.jar
If you're not using the JDK 1.3, you'll need to include JBoss's jndi.jar file.
Deployment
Unlike standard Java applications or applets, EJBs must be deployed to an EJB container. For the EJB container to know the location of the files that comprise the bean and their respective roles, we must develop a deployment descriptor. Listing 5 shows the contents of our deployment descriptor.
Listing 5 DatabaseManager Deployment Descriptor (ejb-jar.xml)
<?xml version="1.0"?> <!DOCTYPE ejb-jar PUBLIC "-//Sun Microsystems, Inc.// DTD Enterprise JavaBeans 1.1//EN" "http://java.sun.com/j2ee/dtds/ejb-jar_1_1.dtd"> <ejb-jar> <display-name>Database Manager</display-name> <enterprise-beans> <session> <ejb-name>DatabaseManagerBean</ejb-name> <home> com.informit.javasolutions.databasemanager.DatabaseManagerHome </home> <remote> com.informit.javasolutions.databasemanager.DatabaseManager </remote> <ejb-class> com.informit.javasolutions.databasemanager.DatabaseManagerBean </ejb-class> <session-type>Stateless</session-type> <transaction-type>Container</transaction-type> <!-- Provide a JNDI link to the database so that this session bean can access it through the following string: java:comp/env/jdbc/InformIT Now it is the responsibility of the EJB Container to map jndi/InformIT to the actual JNDI database name. --> <resource-ref> <description>Database connection pool</description> <res-ref-name>jdbc/InformIT</res-ref-name> <res-type>javax.sql.DataSource</res-type> <res-auth>Container</res-auth> </resource-ref> </session> </enterprise-beans> </ejb-jar>
All deployment descriptors are named ejb-jar.xml and have an <enterprise-beans> tag that defines all entity beans and session beans. Entity beans are defined by an <entity> tag and session beans are defined by a <session> tag. In the DatabaseManager deployment descriptor we have one session bean, and hence one <session> tag.
The <description> tag describes this entity bean, for use with some GUI deployment applications. The <ejb-name> tag names the bean; this name references this bean elsewhere in the ejb-jar.xml file as well as in custom deployment files. The <home> tag defines the fully qualified name of the entity bean's home interface, the <remote> tag defines the fully qualified name of the entity bean's remote interface, and the <ejb-class> tag defines the fully qualified name of the session bean's bean class. The <session-type> tag defines whether the session is "stateless" or "stateful"; in our case, this entry is "stateless".
Inside the <session> tag we have defined a <resource-ref> tag. This tag provides a reference to a resource that's available from within this bean (usually a database connection or another EJB). In this case, we make a javax.sql.DataSource reference available in the DatabaseManager session bean with the name "java:comp/env/jdbc/InformIT". We'll resolve this to our SQLServerPool in the JBoss custom deployment descriptor (jboss.xml).
The second half of this deployment is JBoss's own deployment descriptor (jboss.xml); see Listing 6.
Listing 6 DatabaseManager Deployment Descriptor (jboss.xml)
<?xml version="1.0" encoding="Cp1252"?> <jboss> <secure>false</secure> <container-configurations /> <resource-managers> <resource-manager> <res-name>jdbc/InformIT</res-name> <res-jndi-name>SQLServerPool</res-jndi-name> </resource-manager> </resource-managers> <enterprise-beans> <session> <ejb-name>DatabaseManagerBean</ejb-name> <jndi-name>db/DatabaseManager</jndi-name> <configuration-name></configuration-name> </session> </enterprise-beans> </jboss>
The JBoss custom deployment descriptor has the root node <jboss>. To resolve our database connection resource reference, we have to create a <resource-manager> that maps a resource name, <res-name> (that the EJB will use), to a JNDI name, <res-jndi-name>. In this case we mapped "java:comp/env/jdbc/InformIT" to "SQLServerPool".
If you don't have a jboss.xml file in your deployment, one is automatically created, but if you define your own you must define the beans that are in your ejb-jar.xml file. The only modification we make to the deployment is that we change the JNDI name of our session bean using the <jndi-name> tag in our <session> tag; we changed the name from "DatabaseManager" to "db/DatabaseManager".
Once you have these deployment descriptors and your classes in place, you must package your EJB into a JAR file with the following directory structure:
com/informit/javasolutions/databasemanager/DatabaseManager.class com/informit/javasolutions/databasemanager/DatabaseManagerHome.class com/informit/javasolutions/databasemanager/DatabaseManagerBean.class com/informit/javasolutions/database/UserInfo.class com/informit/javasolutions/database/CompanyInfo.class META-INF/ejb-jar.xml META-INF/jboss.xml
From the folder that contains your com folder, you can build this JAR file with the following command:
jar cf db.jar com/informit/javasolutions/databasemanager/*.class com/informit/javasolutions/database/*.class META-INF/*.xml
This will build a file db.jar that contains your entity bean. The last step is to copy this file to the JBoss deploy directory. If you have JBoss running, you can watch the deployment on the text display; if not, start JBoss by executing its run.bat file from its bin directory and look for your bean! You should see something similar to the following:
... [J2EE Deployer] Create application db.jar [J2EE Deployer] Installing EJB package: db.jar [J2EE Deployer] Starting module db.jar [Container factory] Deploying:file:/D:/jBoss-2.0_FINAL/bin/../tmp/ deploy/db.jar/ejb1010.jar [Verifier] Verifying file:/D:/jBoss-2.0_FINAL/bin/../tmp/deploy/ db.jar/ejb1010.jar [Container factory] Deploying DatabaseManagerBean [Container factory] Deployed application: file:/D:/jBoss-2.0_FINAL/ bin/../tmp/deploy/db.jar/ejb1010.jar [J2EE Deployer] J2EE application: file:/D:/jBoss-2.0_FINAL/deploy/ db.jar is deployed.
If you see any exceptions, read through them and try to troubleshoot the problem; most errors are fairly easy to interpret and involve a missing file from the JAR file, a misspelling, or a case-sensitivity issue (uppercase versus lowercase).
Test Client
Once you have your session bean, it's time to write a client that exercises its methods. Listing 7 shows the complete source code for the test client.
Listing 7 Test Client (TestClient.java)
import com.informit.javasolutions.databasemanager.DatabaseManager; import com.informit.javasolutions.databasemanager.DatabaseManagerHome; import com.informit.javasolutions.database.CompanyInfo; import com.informit.javasolutions.database.UserInfo; // Import the EJB classes import java.rmi.RemoteException; import javax.ejb.*; // Import the JNDI classes import javax.naming.*; import javax.rmi.PortableRemoteObject; // Import the Java Collection classes import java.util.*; public class TestClient { public static void main( String[] args ) { System.setProperty( "java.naming.factory.initial", "org.jnp.interfaces.NamingContextFactory"); System.setProperty( "java.naming.provider.url", "localhost:1099"); try { // Get a naming context InitialContext jndiContext = new InitialContext(); System.out.println("Got context"); // Get a reference to the Interest Bean Object ref = jndiContext.lookup( "db/DatabaseManager" ); System.out.println("Got reference"); // Get a reference from this to the Bean's Home interface DatabaseManagerHome home = ( DatabaseManagerHome ) PortableRemoteObject.narrow( ref, DatabaseManagerHome.class ); DatabaseManager db = home.create(); if( args.length >= 1 ) { // Create some companies for( int i=1; i<=20; i++ ) { CompanyInfo company = new CompanyInfo( i, "Company " + i ); db.addCompany( company ); } // Create some users for( int i=1; i<=20; i++ ) { UserInfo user = null; if( i <= 10 ) user = new UserInfo( i, "User " + i, 1 ); else user = new UserInfo( i, "User " + i, 2 ); db.addUser( user ); } } // Find our companies and users CompanyInfo[] companies = db.findCompanies(); for( int i=0; i<companies.length; i++ ) { System.out.println( "Company: " + companies[ i ].getName() ); int userCount = db.getNumberOfUsers( companies[ i ].getId() ); System.out.println( " Users: " + userCount ); UserInfo[] users = db.findUsersForCompany( companies[ i ].getId() ); for( int j=0; j<users.length; j++ ) { System.out.println( " User: " + users[ j ].getName() ); } } } catch( Exception e ) { e.printStackTrace(); } } }
To connect to the JBoss JNDI server, we must set a couple of system properties:
System.setProperty( "java.naming.factory.initial", "org.jnp.interfaces.NamingContextFactory"); System.setProperty( "java.naming.provider.url", "localhost:1099");
The naming factory is the class that JNDI will use to locate the JBoss JNDI server and the provider URL is the network location of the machine on which JBoss is running. In our case, we're running on the same machine, and hence we'll use "localhost" on the standard RMI port 1099.
Next, we create an instance of the javax.naming.InitialContext class; this uses the system properties we specified to connect to JBoss. To find the bean we're looking for (DatabaseManagerBean), we use the InitialContext lookup() method; this returns an object reference that we need to resolve to the actual entity bean's home interface. You may read in many books that you can cast this object directly to the home interface, and this will work in almost all cases, but because EJB can be used with CORBA objects through RMI/IIOP, the object is not necessarily a Java object and must be "narrowed." The javax.rmi.PortableRemoteObject class provides a static method narrow() that tests to make sure that the conversion is permissible and returns the correct object.
Once we have a reference to the home interface, we need to create an instance of a class implementing the session bean's remote interface:
DatabaseManager db = home.create();
From there, we create some companies and some users for the first two companies (if any command-line argument is specified), and then we query for the company and its list of users.