October 21, 2014
Hot Topics:
RSS RSS feed Download our iPhone app

Developing a BMP Bean

  • July 31, 2003
  • By Saleem Siddiqui, Michael Landy, & Jeff Swisher
  • Send Email »
  • More Articles »

This material is from the book JBuilder Developer's Guide.

© Copyright Sams Publishing. All rights reserved.


Developing a BMP Bean

In the preceding article, 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:

Bean managed persistence requires you to implement a specific interface. Ultimately, this interface maps to relational SQL, (see Table 1).

Table 1 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 1).

Listing 1 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 2).

Listing 2 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 2 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 2 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 3).

Listing 3 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 4).

Listing 4 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>




Page 1 of 2



Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Sitemap | Contact Us

Rocket Fuel