예제: 레거시 EJB 액세스 Bean 사용

이 예제에서는 세 개의 기존 CMP 엔티티 Bean에 대한 EJB 1.1 액세스 Bean을 설명합니다.

액세스 Bean을 작성하는 방법을 알려면 다음의 이름을 사용하는 세 개의 기존 CMP EJB 각각에 대한 액세스 Bean을 작성해야 하는 간단한 EJB 1.1 예제를 고려해 보십시오.

이러한 EJB의 CMP 필드 및 관계와 각 EJB에 대해 생성해야 하는 액세스 Bean의 유형은 다음 표와 같습니다.

EJB 이름 CMP 필드 관계 액세스 Bean 유형 액세스 Bean 이름
Employee ID name salary Manager의 수퍼 클래스. Department와 1:N 연관에 참여함(Employee에는 하나의 부서가 있지만 Department에는 여러 직원이 있음) Rowset EmployeeAccessBean
Manager parkinglotnum Employee의 서브클래스(Employee에서 상속됨) 복사 헬퍼 ManagerAccessBean
Department ID name projectcode Employee와 1:N 연관에 참여함(Department에는 여러 직원이 있지만 Employee에는 하나의 부서만 있음) 복사 헬퍼 DepartmentAccessBean

이 주제의 나머지에서는 다음 세 개의 액세스 Bean에 대한 확장 샘플 코드가 표시됩니다.

샘플 코드에는 EJB 인터페이스, 액세스 Bean 메소드 시그너처 및 클라이언트 프로그램이 있습니다.

이 예제에서는 모든 클래스가 empexample 패키지에 있으며 EJB가 EJB 그룹 ABExample에 있다고 가정하십시오. Department, Employee 및 Manager 액세스 Bean과 연관된 샘플 코드는 아래의 절을 참조하십시오.

EJB 인터페이스

다음 코드 샘플에 EJB 인터페이스가 제공되어 있습니다.

public interface Employee extends javax.ejb.EJBObject {
  empexample.Department getDepartment() throws java.rmi.RemoteException,
     javax.ejb.FinderException;
  empexample.DepartmentKey getDepartmentKey() throws java.rmi.RemoteException;
  java.lang.String getName() throws java.rmi.RemoteException;
  float getSalary() throws java.rmi.RemoteException;
  void privateSetDepartmentKey(empexample.DepartmentKey inKey) throws
     java.rmi.RemoteException;
  void secondarySetDepartment(empexample.Department aDepartment) throws
     java.rmi.RemoteException;
  void setDepartment(empexample.Department aDepartment) throws
     java.rmi.RemoteException;
  void setName(java.lang.String newValue) throws java.rmi.RemoteException;
  void setSalary(float newValue) throws java.rmi.RemoteException;
}
public interface EmployeeHome extends javax.ejb.EJBHome {
  empexample.Employee create(int argId) throws javax.ejb.CreateException,
     java.rmi.RemoteException;
  empexample.Employee create(int argId, int depId) throws
     javax.ejb.CreateException, java.rmi.RemoteException;
  empexample.Employee findByPrimaryKey(empexample.EmployeeKey key) throws
     java.rmi.RemoteException, javax.ejb.FinderException;
  java.util.Enumeration findEmployeeByDepartment(empexample.DepartmentKey inKey) throws
     java.rmi.RemoteException, javax.ejb.FinderException;
}
public interface Manager extends Employee {
  int getParkinglotnum() throws java.rmi.RemoteException;
  void setParkinglotnum(int newValue) throws java.rmi.RemoteException;
}
public interface ManagerHome extends javax.ejb.EJBHome {
  empexample.Manager create(int argId) throws javax.ejb.CreateException,
     java.rmi.RemoteException;
  empexample.Manager findByPrimaryKey(EmployeeKey key) throws
     java.rmi.RemoteException, javax.ejb.FinderException;
}
public interface Department extends javax.ejb.EJBObject {
  void addEmployee(empexample.Employee anEmployee) throws
     java.rmi.RemoteException;
  java.util.Enumeration getEmployee() throws java.rmi.RemoteException,
     javax.ejb.FinderException;
  java.lang.String getName() throws java.rmi.RemoteException;
  int getProjectcode() throws java.rmi.RemoteException;
  void secondaryAddEmployee(empexample.Employee anEmployee) throws
     java.rmi.RemoteException;
  void secondaryRemoveEmployee(empexample.Employee anEmployee) throws
      java.rmi.RemoteException;
  void setName(java.lang.String newValue) throws java.rmi.RemoteException;
  void setProjectcode(int newValue) throws java.rmi.RemoteException;
}
public interface DepartmentHome extends javax.ejb.EJBHome {
  empexample.Department create(int argId) throws javax.ejb.CreateException,
     java.rmi.RemoteException;
  empexample.Department findByPrimaryKey(empexample.DepartmentKey key) throws
     java.rmi.RemoteException, javax.ejb.FinderException;
}

EJB 액세스 Bean 메소드 시그너처

샘플 코드의 이 부분에서는 세 개의 CMP EJB가 완료되었다고 가정하십시오. Manager EJB가 Employee EJB에서 상속되고 Employee EJB는 Department EJB와 1:N 연관이 있습니다.

이제 액세스 Bean을 생성합니다. Department 및 Manager EJB의 복사 헬퍼와 Employee EJB의 rowset입니다. Getter 및 Setter의 문자열 변환기를 사용하지 않고 연관된 CMP EJB 키의 Getter를 제외한 모든 CMP 필드가 캐시되었다고 가정할 수 있습니다.

다음의 코드 샘플은 액세스 Bean의 메소드 시그너처를 제공합니다.

public class EmployeeAccessBean extends com.ibm.ivj.ejb.runtime.AbstractEntityAccessBean
   implements EmployeeAccessBeanData {
  /**
   * Zero argument constructor used to initialize the access bean.
   *
   * This constructor corresponds to the following home interface method:
   *
   * public abstract empexample.Employee empexample.EmployeeHome.create(int) throws
   *    javax.ejb.CreateException,java.rmi.RemoteException
   *
   * The home interface method properties need to be set by calling
   * the following setter methods before calling any business methods:
   * setInit_argId( int )
   * setInit_depId( int )
   */
   public EmployeeAccessBean()
   public EmployeeAccessBean(empexample.EmployeeKey arg0) throws
      java.rmi.RemoteException, javax.ejb.FinderException,
      javax.naming.NamingException
   public EmployeeAccessBean ( javax.ejb.EJBObject o ) throws
      java.rmi.RemoteException
   public EmployeeAccessBean ( int arg0 ) throws javax.ejb.CreateException,
      java.rmi.RemoteException, javax.naming.NamingException 
   public void commitCopyHelper() throws java.rmi.RemoteException,
      javax.ejb.CreateException, javax.ejb.FinderException, 
      javax.naming.NamingException
   protected String defaultJNDIName()
   private empexample.EmployeeHome ejbHome() throws
      java.rmi.RemoteException, javax.naming.NamingException
   private empexample.Employee ejbRef() throws java.rmi.RemoteException
   public java.util.Enumeration findEmployeeByDepartment(empexample.DepartmentKey arg0)
      throws java.rmi.RemoteException, javax.ejb.FinderException, 
      javax.naming.NamingException
   public empexample.DepartmentAccessBean getDepartment() throws
      java.rmi.RemoteException, javax.ejb.FinderException,
      javax.ejb.CreateException, javax.naming.NamingException
   public empexample.DepartmentKey getDepartmentKey() throws
      java.rmi.RemoteException, javax.ejb.CreateException,
      javax.naming.NamingException
   public java.lang.String getName() throws java.rmi.RemoteException,
      javax.ejb.CreateException, javax.ejb.FinderException,
      javax.naming.NamingException
   public float getSalary() throws java.rmi.RemoteException,
      javax.ejb.CreateException, javax.ejb.FinderException,
      javax.naming.NamingException
   protected void instantiateEJB() throws javax.ejb.CreateException,
      java.rmi.RemoteException, javax.naming.NamingException
   protected boolean instantiateEJBByPrimaryKey() throws
      java.rmi.RemoteException, javax.ejb.CreateException,
      javax.naming.NamingException
   public void privateSetDepartmentKey(empexample.DepartmentKey arg0) throws
      java.rmi.RemoteException, javax.ejb.CreateException,
      javax.naming.NamingException
   public void refreshCopyHelper() throws java.rmi.RemoteException,
      javax.ejb.CreateException, javax.ejb.FinderException,
      javax.naming.NamingException
   public void secondarySetDepartment(empexample.Department arg0) throws
      java.rmi.RemoteException, javax.ejb.CreateException,
      javax.naming.NamingException
   public void setDepartment(empexample.Department arg0) throws
      java.rmi.RemoteException, javax.ejb.CreateException,
      javax.naming.NamingException
   public void setInit_argId( int newValue )
   public void setInit_depId( int newValue )
   public void setName( java.lang.String newValue )
   public void setSalary( float newValue )
}
public class ManagerAccessBean extends
   com.ibm.ivj.ejb.runtime.AbstractEntityAccessBean implements ManagerAccessBeanData {
  /**
   * Zero argument constructor used to initialize the access bean.
   *
   * This constructor corresponds to the following home interface method:
   *
   * public abstract empexample.Manager empexample.ManagerHome.create(int) throws
   *    javax.ejb.CreateException, java.rmi.RemoteException
   *
   * The home interface method properties need to be set by calling
   * the following setter methods before calling any business methods:
   * setInit_argId( int )
   */
   public ManagerAccessBean ()
   public ManagerAccessBean(empexample.EmployeeKey arg0) throws
      java.rmi.RemoteException, javax.ejb.FinderException,
      javax.naming.NamingException
   public ManagerAccessBean ( javax.ejb.EJBObject o ) throws
      java.rmi.RemoteException
   public void commitCopyHelper() throws java.rmi.RemoteException,
      javax.ejb.CreateException, javax.ejb.FinderException,
      javax.naming.NamingException
   protected String defaultJNDIName()
   private empexample.ManagerHome ejbHome() throws java.rmi.RemoteException,
      javax.naming.NamingException
   private empexample.Manager ejbRef() throws java.rmi.RemoteException
   public empexample.DepartmentAccessBean getDepartment() throws
      java.rmi.RemoteException, javax.ejb.FinderException, 
      javax.ejb.CreateException, javax.naming.NamingException
   public empexample.DepartmentKey getDepartmentKey() throws 
      java.rmi.RemoteException, javax.ejb.CreateException, 
      javax.naming.NamingException
   public java.lang.String getName() throws java.rmi.RemoteException, 
      javax.ejb.CreateException, javax.ejb.FinderException, 
      javax.naming.NamingException
   public int getParkinglotnum() throws java.rmi.RemoteException, 
      javax.ejb.CreateException, javax.ejb.FinderException, 
      javax.naming.NamingException
   public float getSalary() throws java.rmi.RemoteException, 
      javax.ejb.CreateException, javax.ejb.FinderException, 
      javax.naming.NamingException 
   protected void instantiateEJB() throws javax.ejb.CreateException,
      java.rmi.RemoteException, javax.naming.NamingException
   protected boolean instantiateEJBByPrimaryKey() throws
      java.rmi.RemoteException, javax.ejb.CreateException,
      javax.naming.NamingException
   public void privateSetDepartmentKey(empexample.DepartmentKey arg0) throws
      java.rmi.RemoteException, javax.ejb.CreateException,
      javax.naming.NamingException
   public void refreshCopyHelper() throws java.rmi.RemoteException,
      javax.ejb.CreateException, javax.ejb.FinderException, 
      javax.naming.NamingException
   public void secondarySetDepartment(empexample.Department arg0) throws
      java.rmi.RemoteException, javax.ejb.CreateException, 
      javax.naming.NamingException
   public void setDepartment(empexample.Department arg0) throws
      java.rmi.RemoteException, javax.ejb.CreateException, 
      javax.naming.NamingException
   public void setInit_argId( int newValue )
   public void setName( java.lang.String newValue )
   public void setParkinglotnum( int newValue )
   public void setSalary( float newValue )
}
public class DepartmentAccessBean 
   extends com.ibm.ivj.ejb.runtime.AbstractEntityAccessBean
   implements DepartmentAccessBeanData {
  /**
   * Zero argument constructor used to initialize the access bean.
   *
   * This constructor corresponds to the following home interface method:
   *
   * public abstract empexample.Department empexample.DepartmentHome.create(int)
   *    throws javax.ejb.CreateException,java.rmi.RemoteException
   *
   * The home interface method properties need to be set by calling
   * the following setter methods before calling any business methods:
   * setInit_argId( int )
   */
   public DepartmentAccessBean ()
   public DepartmentAccessBean(empexample.DepartmentKey arg0) throws
      java.rmi.RemoteException, javax.ejb.FinderException, 
      javax.naming.NamingException
   public DepartmentAccessBean ( javax.ejb.EJBObject o ) throws 
      java.rmi.RemoteException
   public void addEmployee(empexample.Employee arg0) throws
      java.rmi.RemoteException, javax.ejb.CreateException,
      javax.naming.NamingException
   public void commitCopyHelper() throws java.rmi.RemoteException,
      javax.ejb.CreateException, javax.ejb.FinderException,
      javax.naming.NamingException
   protected String defaultJNDIName()
   private empexample.DepartmentHome ejbHome() throws
      java.rmi.RemoteException, javax.naming.NamingException
   private empexample.Department ejbRef() throws
      java.rmi.RemoteException
   public java.util.Enumeration getEmployee() throws java.rmi.RemoteException,
      javax.ejb.FinderException, javax.ejb.CreateException, 
      javax.naming.NamingException
   public java.lang.String getName() throws java.rmi.RemoteException,
      javax.ejb.CreateException, javax.ejb.FinderException, 
      javax.naming.NamingException
   public int getProjectcode() throws java.rmi.RemoteException, 
      javax.ejb.CreateException, javax.ejb.FinderException, 
      javax.naming.NamingException
   protected void instantiateEJB() throws javax.ejb.CreateException, 
      java.rmi.RemoteException, javax.naming.NamingException
   protected boolean instantiateEJBByPrimaryKey() throws 
       java.rmi.RemoteException, javax.ejb.CreateException, 
       javax.naming.NamingException
   public void refreshCopyHelper() throws java.rmi.RemoteException, 
       javax.ejb.CreateException, javax.ejb.FinderException,
       javax.naming.NamingException
   public void secondaryAddEmployee(empexample.Employee arg0) throws
       java.rmi.RemoteException, javax.ejb.CreateException, 
       javax.naming.NamingException
   public void secondaryRemoveEmployee(empexample.Employee arg0) throws
       java.rmi.RemoteException, javax.ejb.CreateException, 
       javax.naming.NamingException
   public void setInit_argId( int newValue ) 
   public void setName( java.lang.String newValue )
   public void setProjectcode( int newValue )
}

EJB 클라이언트 프로그램

다음의 코드 샘플에서 EJB 클라이언트 프로그램은 액세스 Bean에서 다양한 조작을 수행 중인 것으로 표시됩니다.

package empexample;

import javax.ejb.*;
import com.ibm.ivj.ejb.runtime.*;

public class EmpDepTest {

/**
 * Simple test of the Employee, Department, and Manager
 * access beans.
 *
 * @param args an array of command-line arguments
 * args[0] = Employee ID#
 * args[1] = Employee Name
 * args[2] = Employee Salary
 * args[3] = Department ID#
 * args[4] = Parking lot# (optional)
 */

public static void main(java.lang.String[] args) {

    EmployeeAccessBean empab = null;
    ManagerAccessBean mgrab = null;
    DepartmentAccessBean depab = null;
    int empid;
    String empname;
    float empsalary;
    int mgrparknum;
    int depid;

    try {
        empid = Integer.parseInt(args[0]);
        empname = args[1];
        empsalary = Float.parseFloat(args[2]);
        depid = Integer.parseInt(args[3]);
        mgrparknum = Integer.parseInt(args[4]);

        // Attempt to create a new employee with given info
        try {
            empab = new EmployeeAccessBean();
            empab.setInit_argId(empid);
            empab.setInit_depId(depid);

            

            // Set the various attributes (gets written to cache)
            empab.setName(empname);
            empab.setSalary(empsalary);

            // Flush the cache to the server
            empab.commitCopyHelper();
        }

        // If duplicate key exception occurs, find the pre-existing
        // instance instead
        catch ( DuplicateKeyException dke ) {
                empab = new EmployeeAccessBean(new EmployeeKey(empid));

                // Fill the cache with all the attributes
                empab.refreshCopyHelper();

                // Update the pre-existing Employee with new info
                // and update the entity bean by flushing the cache
                empab.setName(empname); 
                empab.setSalary(empsalary);
                empab.commitCopyHelper();
        }

        // Display employee info
        // Get the Employee bean's key (assume key class has
        // getters for key fields)
        EmployeeKey empkey = (EmployeeKey) empab.__getKey();
        System.out.println("Employee ID#: " + empkey.getId());
        System.out.println("Employee Name: " + empab.getName());
        System.out.println("Employee Salary: " + empab.getSalary());
        
        // Get the Department access bean (for associated EJB) for
        // this Employee
        depab = empab.getDepartment();
        if ( depab != null ) {
            DepartmentKey depkey = (DepartmentKey) depab.__getKey();

            // Find all the employees in this department
            // This is also shows the use of the new AccessBeanEnumeration
            // class which is a special enumeration class that only
            // instantiates the EJB object when nextElement() is called.
            // All access bean finder methods returning Enumerations of 
            // EJBObject's now return this special enumeration class
            System.out.println("\nFinding all employees for department "  
                                                  + depab.getName());
            AccessBeanEnumeration aem =
                (AccessBeanEnumeration) empab.findEmployeeByDepartment(depkey);

            // Use an access bean table (rowset) to organize and manipulate the
            // enumeration of Employee access beans.
            // Usually, a session bean would first create this table before
            // passing it on to a JSP where the enumeration of access beans
            // can be handled like a rowset using indexes.
            // Rows (or EJB instances) can then be added or removed from the
            // rowset.
            EmployeeAccessBeanTable emptable = new EmployeeAccessBeanTable();

            // One possible way of filling the table is to call the method below
            //emptable.setEmployeeAccessBean(aem);

            // This is another way
            while ( aem.hasMoreElements() ) {
                  EmployeeAccessBean empab_temp = (EmployeeAccessBean) aem.nextElement();
                  emptable.addRow(empab_temp);
                  empab_temp.refreshCopyHelper();
                  System.out.println("    Employee Name: " + empab_temp.getName());
                  System.out.println("    Employee Salary: " + empab_temp.getSalary());
            }

            // Once the table is built, the client can go about working with
            // with it and performing various operations on it without any
            // server-side communications

        }

        else {
             System.out.println("Could not find a department for employee id#" + empid);
        }

    }


    catch ( Exception e ) {
            e.printStackTrace();
    }

}
}

피드백