Developing a BMP Bean
In the preceding section, we developed a CMP bean in which the container handled all the persistence. We will now look at the process for building a BMP bean and contrast the process from the CMP bean. For a BMP bean, we must produce the appropriate persistence code for our bean instead of the container accomplishing that task for us.
Most of the changes from EJB 1.1 to EJB 2.0 specifications focused on container managed persistence. There were a few changes to bean managed persistence. The changes are basically two different items:
The introduction of local interfaces for use within these beans allows for fine-grained objects to be used without a detriment to performance.
The home interface can contain more than just accessors, mutators, and finder methods; it can contain business methods. These business methods can contain implementations that reference a group of entities versus a single entity.
Bean managed persistence requires you to implement a specific interface. Ultimately, this interface maps to relational SQL, (see Table 23.3).
Table 23.3 SQLStatements Relate to Different Relational SQL
Method |
SQL Statement |
ejbCreate |
INSERT |
ejbFindByPrimaryKey |
SELECT |
ejbFindByLastName |
SELECT |
ejbFindInRange |
SELECT |
ejbLoad |
SELECT |
ejbRemove |
DELETE |
ejbStore |
UPDATE |
Rather than start over with a new example, we will use the Employee bean we constructed using a CMP bean. Ultimately, this gives us the ability to compare the new BMP bean to the previously created CMP bean.
Defining the Home Interface
The home interface should look exactly the same as the CMP bean's home interface. This allows the user of the bean to not know whether the bean is CMP or BMP, nor should she be concerned (see Listing 23.13).
Listing 23.13 Home Interface for Our BMP Bean
package entitybeansample; import javax.ejb.*; import java.util.*; public interface EmployeeBMPHome extends javax.ejb.EJBLocalHome { public EmployeeBMP create(Short empNo) throws CreateException; public EmployeeBMP findByPrimaryKey(Short empNo) throws FinderException; }
Defining the Remote Interface
The remote interface should look identical also. This interface provides us access to all the fine-grained attributes required (see Listing 23.14).
Listing 23.14 Remote Interface for Our Employee BMP Entity Bean
package entitybeansample; import javax.ejb.*; import java.util.*; import java.rmi.*; import java.sql.*; import java.math.*; public interface EmployeeBMPRemote extends javax.ejb.EJBObject { public Short getEmpNo() throws RemoteException; public void setFirstName(String firstName) throws RemoteException; public String getFirstName() throws RemoteException; public void setLastName(String lastName) throws RemoteException; public String getLastName() throws RemoteException; public void setPhoneExt(String phoneExt) throws RemoteException; public String getPhoneExt() throws RemoteException; public void setHireDate(Timestamp hireDate) throws RemoteException; public Timestamp getHireDate() throws RemoteException; public void setDeptNo(String deptNo) throws RemoteException; public String getDeptNo() throws RemoteException; public void setJobCode(String jobCode) throws RemoteException; public String getJobCode() throws RemoteException; public void setJobGrade(Short jobGrade) throws RemoteException; public Short getJobGrade() throws RemoteException; public void setJobCountry(String jobCountry) throws RemoteException; public String getJobCountry() throws RemoteException; public void setSalary(BigDecimal salary) throws RemoteException; public BigDecimal getSalary() throws RemoteException; public void setFullName(String fullName) throws RemoteException; public String getFullName() throws RemoteException; }
Implementing the Bean
This section contains the complete implementation of our persistence logic. As we implement this interface, we have to be sensitive to the exceptions we need to use. Table 23.4 summarizes the exceptions of the javax.ejb package. All these exceptions are application exceptions, except for the NoSuchEntityException and the EJBException, which are system exceptions.
Table 23.4 Exception Summary for Use with Bean-Managed Persistence
Method Name |
Exception It Throws |
Reason for Throwing |
ejbCreate |
CreateException |
An input parameter is invalid. |
ejbFindByPrimary Key (and other finder methods that return a single object) |
ObjectNotFoundException (subclass of FinderException) |
The database row for the requested entity bean cannot be found. |
ejbRemove |
RemoveException |
The entity bean's row cannot be deleted from the database. |
ejbLoad |
NoSuchEntityException |
The database row to be loaded cannot be found. |
ejbStore |
NoSuchEntityException |
The database row to be updated cannot be found. |
(all methods) |
EJBException |
A system problem has been encountered. |
The CMP bean was basically empty, but in a BMP bean, we need to implement the services required. As we continue with our employee example, we need to implement the bean interface generated by the EJB Designer wizards (see Listing 23.15).
Listing 23.15 Employee BMP Implementation Bean (EmployeeBMPBean.java)
package entitybeansample; import java.sql.*; import javax.ejb.*; import javax.naming.*; import javax.sql.*; public class EmployeeBMPBean implements EntityBean { EntityContext entityContext; java.lang.Short empNo; java.lang.String firstName; java.lang.String lastName; java.lang.String phoneExt; java.sql.Timestamp hireDate; java.lang.String deptNo; java.lang.String jobCode; java.lang.Short jobGrade; java.lang.String jobCountry; java.math.BigDecimal salary; java.lang.String fullName; public java.lang.Short ejbCreate(java.lang.Short empNo) throws CreateException { setEmpNo(empNo); Connection con = null; try { InitialContext initial = new InitialContext(); DataSource ds = (DataSource)initial.lookup( "java:comp/env/jdbc/EmployeeData"); con = ds.getConnection(); PreparedStatement ps = con.prepareStatement( "INSERT INTO employee (empno)" + "values (?)"); ps.setShort(1,empNo.shortValue()); ps.executeUpdate(); return empNo; } catch (SQLException ex) { ex.printStackTrace(); }catch (NamingException ex) { ex.printStackTrace(); throw new CreateException(); }finally { if (con!=null){ try { con.close(); } catch (SQLException ex) { ex.printStackTrace(); } } } return null; } public void ejbPostCreate(java.lang.Short empNo) throws CreateException { /**@todo Complete this method*/ } public void ejbRemove() throws RemoveException { Connection con = null; try { InitialContext initial = new InitialContext(); DataSource ds = (DataSource)initial.lookup( "java:comp/env/jdbc/EmployeeData"); con = ds.getConnection(); PreparedStatement ps = con.prepareStatement("DELETE " + "FROM EMPLOYEE WHERE empno = ?"); ps.setShort(1,getEmpNo().shortValue()); ps.executeUpdate(); } catch (SQLException ex) { ex.printStackTrace(); }catch (NamingException ex) { ex.printStackTrace(); throw new RemoveException(); }finally { if (con!=null){ try { con.close(); } catch (SQLException ex) { ex.printStackTrace(); } } } } //Getters and Setters for all members public void setEmpNo(java.lang.Short empNo) { this.empNo = empNo; } public void setFirstName(java.lang.String firstName) { this.firstName = firstName; } public void setLastName(java.lang.String lastName) { this.lastName = lastName; } public void setPhoneExt(java.lang.String phoneExt) { this.phoneExt = phoneExt; } public void setHireDate(java.sql.Timestamp hireDate) { this.hireDate = hireDate; } public void setDeptNo(java.lang.String deptNo) { this.deptNo = deptNo; } public void setJobCode(java.lang.String jobCode) { this.jobCode = jobCode; } public void setJobGrade(java.lang.Short jobGrade) { this.jobGrade = jobGrade; } public void setJobCountry(java.lang.String jobCountry) { this.jobCountry = jobCountry; } public void setSalary(java.math.BigDecimal salary) { this.salary = salary; } public void setFullName(java.lang.String fullName) { this.fullName = fullName; } public java.lang.Short getEmpNo() { return empNo; } public java.lang.String getFirstName() { return firstName; } public java.lang.String getLastName() { return lastName; } public java.lang.String getPhoneExt() { return phoneExt; } public java.sql.Timestamp getHireDate() { return hireDate; } public java.lang.String getDeptNo() { return deptNo; } public java.lang.String getJobCode() { return jobCode; } public java.lang.Short getJobGrade() { return jobGrade; } public java.lang.String getJobCountry() { return jobCountry; } public java.math.BigDecimal getSalary() { return salary; } public java.lang.String getFullName() { return fullName; } //Find an individual instance and return the primary key public java.lang.Short ejbFindByPrimaryKey(java.lang.Short empNo) throws FinderException { Connection con = null; try { InitialContext initial = new InitialContext(); DataSource ds = (DataSource)initial.lookup( "java:comp/env/jdbc/EmployeeData"); con = ds.getConnection(); PreparedStatement ps = con.prepareStatement("SELECT id FROM EMPLOYEE" + "WHERE empno = ?"); ps.setShort(1,empNo.shortValue()); ResultSet rs = ps.executeQuery(); if (!rs.next()){ throw new ObjectNotFoundException(); } return empNo; } catch (SQLException ex) { ex.printStackTrace(); }catch (NamingException ex) { ex.printStackTrace(); throw new EJBException(ex); } finally { if (con!=null){ try { con.close(); } catch (SQLException ex) { ex.printStackTrace(); } } } return null; } //Load a single instance from the datasource public void ejbLoad() { Connection con = null; try { InitialContext initial = new InitialContext(); DataSource ds = (DataSource)initial.lookup( "java:comp/env/jdbc/EmployeeData"); con = ds.getConnection(); PreparedStatement ps = con.prepareStatement( "SELECT EmpNo,DeptNo,FirstName," + "FullName,HireDate,JobCode,JobCountry,JobGrade,LastName, PhoneExt,Salary " + "FROM EMPLOYEE WHERE empno = ?"); ps.setShort(1,getEmpNo().shortValue()); ResultSet rs = ps.executeQuery(); if (!rs.next()){ throw new EJBException("Object not found!"); } setDeptNo(rs.getString(2)); setFirstName(rs.getString(3)); setFullName(rs.getString(4)); setHireDate(rs.getTimestamp(5)); setJobCode(rs.getString(6)); setJobCountry(rs.getString(7)); setJobGrade(new java.lang.Short(rs.getShort(8))); setLastName(rs.getString(9)); setPhoneExt(rs.getString(10)); setSalary(rs.getBigDecimal(11)); } catch (SQLException ex) { ex.printStackTrace(); }catch (NamingException ex) { ex.printStackTrace(); throw new EJBException(ex); } finally { if (con!=null){ try { con.close(); } catch (SQLException ex) { ex.printStackTrace(); } } } } //Pasivate data to the datasource public void ejbStore() { Connection con = null; try { InitialContext initial = new InitialContext(); DataSource ds = (DataSource)initial.lookup( "java:comp/env/jdbc/EmployeeData"); con = ds.getConnection(); PreparedStatement ps = con.prepareStatement("Update employee " + "set DeptNo = ?, FirstName = ?, FullName = ?, HireDate = ?," + "JobCode = ?, JobCountry = ?, JobGrade = ?, LastName = ?," + "PhoneExt = ?, Salary = ? where empno = ?"); ps.setString(1,getDeptNo()); ps.setString(2,getFirstName()); ps.setString(3,getFirstName()); ps.setString(4,getFullName()); ps.setTimestamp(5,getHireDate()); ps.setString(6,getJobCode()); ps.setString(7,getJobCountry()); ps.setShort(8,getJobGrade().shortValue()); ps.setString(9,getLastName()); ps.setString(10,getPhoneExt()); ps.setBigDecimal(11,getSalary()); ps.setShort(12,empNo.shortValue()); ps.executeUpdate(); } catch (SQLException ex) { ex.printStackTrace(); }catch (NamingException ex) { ex.printStackTrace(); throw new EJBException(); }finally { if (con!=null){ try { con.close(); } catch (SQLException ex) { ex.printStackTrace(); } } } } public void ejbActivate() { } public void ejbPassivate() { } public void unsetEntityContext() { this.entityContext = null; } public void setEntityContext(EntityContext entityContext) { this.entityContext = entityContext; } }
Deployment Descriptor
The deployment descriptor differs only slightly from the container managed persistence bean created earlier. For example, the <persistence-type> changed from Container to Bean (see Listing 23.16).
Listing 23.16 Deployment Descriptor for Our Entity Beans
<?xml version="1.0" encoding="UTF-8"?> <!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> <display-name>Employee1</display-name> <ejb-name>EmployeeBMP</ejb-name> <home>entitybeansample.EmployeeBMPRemoteHome</home> <remote>entitybeansample.EmployeeBMPRemote</remote> <local-home>entitybeansample.EmployeeBMPHome</local-home> <local>entitybeansample.EmployeeBMP</local> <ejb-class>entitybeansample.EmployeeBMPBean</ejb-class> <persistence-type>Bean</persistence-type> <prim-key-class>java.lang.Short</prim-key-class> <reentrant>False</reentrant> <abstract-schema-name>Employee1</abstract-schema-name> </entity> </enterprise-beans> <assembly-descriptor> <container-transaction> <method> <ejb-name>EmployeeBMP</ejb-name> <method-name>*</method-name> </method> <trans-attribute>Required</trans-attribute> </container-transaction> </assembly-descriptor> </ejb-JAR>
Deploying Your Entity Bean
Deploying your bean is no different from deploying a container managed persistent bean. Just like a CMP bean, the home interface is used to create, find, and remove instances of the entity.
Using Your Entity Bean
The beauty of using bean managed persistence or container managed persistence is that it gives the bean developer the flexibility to choose the implementation that best meets the persistence requirements. In fact, the client of the bean does not need to be concerned with the method of persistence, only that the persistence is accomplished. For example, using the same client used to test our container managed persistent bean, we can now test our bean managed persistent bean. The only change we need to make to the client is to change from using the Employee entity bean to the EmployeeBMP (see Listing 23.17).
Listing 23.17 Test Client to Exercise Our New Entity Bean (EmployeeTestClient.java)
package entitybeansample; import java.math.*; import java.sql.*; import javax.naming.*; import javax.rmi.*; /** * <p>Title: </p> * <p>Description: </p> * <p>Copyright: Copyright (c) 2002</p> * <p>Company: </p> * @author unascribed * @version 1.0 */ public class EmployeeTestClient { static final private String ERROR_NULL_REMOTE = "Remote interface reference is null. It must be created by calling one of the Home interface methods first."; static final private int MAX_OUTPUT_LINE_LENGTH = 100; private boolean logging = true; private EmployeeBMPRemoteHome employeeBMPRemoteHome = null; private EmployeeBMPRemote employeeBMPRemote = null; //Construct the EJB test client public EmployeeTestClient() { long startTime = 0; if (logging) { log("Initializing bean access."); startTime = System.currentTimeMillis(); } try { //get naming context Context ctx = new InitialContext(); //look up jndi name Object ref = ctx.lookup("EmployeeBMPRemote"); //cast to Home interface employeeBMPRemoteHome = (EmployeeBMPRemoteHome) PortableRemoteObject.narrow(ref, EmployeeBMPRemoteHome.class); if (logging) { long endTime = System.currentTimeMillis(); log("Succeeded initializing bean access."); log("Execution time: " + (endTime - startTime) + " ms."); } /* Test your component Interface */ this.findByPrimaryKey(new java.lang.Short("5")); this.getEmpNo(); } catch(Exception e) { if (logging) { log("Failed initializing bean access."); } e.printStackTrace(); } } //----------------------------------------------------------------------- // Methods that use Home interface methods to generate a Remote // interface reference //----------------------------------------------------------------------- public EmployeeBMPRemote create(Short empNo) { long startTime = 0; if (logging) { log("Calling create(" + empNo + ")"); startTime = System.currentTimeMillis(); } try { employeeBMPRemote = employeeBMPRemoteHome.create(empNo); if (logging) { long endTime = System.currentTimeMillis(); log("Succeeded: create(" + empNo + ")"); log("Execution time: " + (endTime - startTime) + " ms."); } } catch(Exception e) { if (logging) { log("Failed: create(" + empNo + ")"); } e.printStackTrace(); } if (logging) { log("Return value from create(" + empNo + "): " + employeeBMPRemote + "."); } return employeeBMPRemote; } public EmployeeBMPRemote findByPrimaryKey(Short empNo) { long startTime = 0; if (logging) { log("Calling findByPrimaryKey(" + empNo + ")"); startTime = System.currentTimeMillis(); } try { employeeBMPRemote = employeeBMPRemoteHome.findByPrimaryKey(empNo); if (logging) { long endTime = System.currentTimeMillis(); log("Succeeded: findByPrimaryKey(" + empNo + ")"); log("Execution time: " + (endTime - startTime) + " ms."); } } catch(Exception e) { if (logging) { log("Failed: findByPrimaryKey(" + empNo + ")"); } e.printStackTrace(); } if (logging) { log("Return value from findByPrimaryKey(" + empNo + "): " + employeeBMPRemote + "."); } return employeeBMPRemote; } //----------------------------------------------------------------------- // Methods that use Remote interface methods to access data through the bean //----------------------------------------------------------------------- public Short getEmpNo() { Short returnValue = null; if (employeeBMPRemote == null) { System.out.println("Error in getEmpNo(): " + ERROR_NULL_REMOTE); return returnValue; } long startTime = 0; if (logging) { log("Calling getEmpNo()"); startTime = System.currentTimeMillis(); } try { returnValue = employeeBMPRemote.getEmpNo(); if (logging) { long endTime = System.currentTimeMillis(); log("Succeeded: getEmpNo()"); log("Execution time: " + (endTime - startTime) + " ms."); } } catch(Exception e) { if (logging) { log("Failed: getEmpNo()"); } e.printStackTrace(); } if (logging) { log("Return value from getEmpNo(): " + returnValue + "."); } return returnValue; } //----------------------------------------------------------------------- // Utility Methods //----------------------------------------------------------------------- private void log(String message) { if (message == null) { System.out.println("-- null"); return ; } if (message.length() > MAX_OUTPUT_LINE_LENGTH) { System.out.println("-- " + message.substring(0, MAX_OUTPUT_LINE_LENGTH) + " ..."); } else { System.out.println("-- " + message); } } //Main method public static void main(String[] args) { EmployeeTestClient client = new EmployeeTestClient(); // Use the client object to call one of the Home interface wrappers // above, to create a Remote interface reference to the bean. // If the return value is of the Remote interface type, you can use it // to access the remote interface methods. You can also just use the // client object to call the Remote interface wrappers. } }
The test client that is generated can then be tweaked or modified to test the implementation. Test clients are not normally designed to fully test a client or live beyond the life of an appropriate client. Typically, when you want long-term test fixtures, you will use JBuilder's Test Case Wizards. See Chapter 5, "Unit Testing," for more information.