Skip Headers

Oracle® Application Server Containers for J2EE Enterprise JavaBeans Developer's Guide
10g Release 2 (10.1.2)
Part No. B15505-01
  Go To Documentation Library
Home
Go To Product List
Solution Area
Go To Table Of Contents
Contents
Go To Index
Index

Previous
Previous
Next
Next
 

Creating Entity Beans

The following steps are an overview of what you must do in creating an entity bean, which are similar to the steps for the session bean, described in Chapter 3, "Implementing Session Beans".

  1. Create the home interfaces for the bean. The home interface defines the create and finder methods, including findByPrimaryKey, for your bean. See "Implement the Entity Bean Home Interface".

  2. Create the component interfaces for the bean. The component interfaces declare the methods that a client can invoke. See "Implement the Entity Bean Component Interfaces".

  3. Define the primary key for the bean. The primary key identifies each entity bean instance and is a serializable class. You can use a simple data type class, such as java.lang.String, or define a complex class, such as one with two or more objects as components of the primary key. See "How to Define and Use Primary Keys for Your Entity Bean".

  4. Implement the bean. See "Implement the Entity Bean Class".

  5. Create the bean deployment descriptor. The deployment descriptor specifies properties for the bean through XML elements. This step is where you identify the data within the bean that is to be managed by the container. See "Persistence Fields" for more information on persistence fields. If these fields describe relationships to other objects, see Chapter 6, "Entity Relationship Mapping".

    Any EJB Container services that you want to configure is also designated in the deployment descriptor. For information about data sources and JTA, see the Oracle Application Server Containers for J2EE Services Guide. For information about security, see the Oracle Application Server Containers for J2EE Security Guide.

    If the persistent data is saved to or restored from a database and you are not using the defaults provided by the container, then you must ensure that the correct tables exist for the bean. In the default scenario, the container creates the table and columns for your data based on deployment descriptor and datasource information.

  6. Create an EJB JAR file containing the bean, component interface, home interface, and the deployment descriptors. Once created, configure the application.xml file, create an EAR file, and deploy the EJB to OC4J.

The following sections demonstrate a simple CMP entity bean. This example continues the use of the employee example, as in other chapters—without adding complexity.

Implement the Entity Bean Home Interface

The home interface is primarily used for retrieving the bean reference, on which the client can request business methods.

  • The local home interface extends javax.ejb.EJBLocalHome.

  • The remote home interface extends javax.ejb.EJBHome.

The home interface must contain a create method, which the client invokes to create the bean instance. The entity bean can have zero or more create methods, each with its own defined parameters. All entity beans must define one or more finder methods, where at least one is a findByPrimaryKey method. Optionally, you can develop other finder methods, which are named find<name>, for the bean.

In addition to creation and retrieval methods, you can provide home interface business methods within the home interface. The functionality within these methods cannot access data of a particular entity object. Instead, the purpose of these methods is to provide a way to retrieve information that is not related to a single entity bean instance. When the client invokes any home interface business method, an entity bean is removed from the pool to service the request. Thus, this method can be used to perform operations on general information related to the bean.

Our employee example provides the local home interface with a create, findByPrimaryKey, findAll, and calcSalary methods. The calcSalary method is a home interface business method that calculates the sum of all employee salaries. It does not access the information of a particular employee, but performs a SQL inquiry against the database for all employees.

Example 4-1 Entity Bean Employee Home Interface

The employee home interface provides a method to create the component interface. It also provides two finder methods: one to find a specific employee by an employee number and one that finds all employees. Last, it supplies a home interface business method, calcSalary, to calculate how much all employees cost the business.

The home interface is required to extend javax.ejb.EJBHome and define the create and findByPrimaryKey methods.

package employee;

import javax.ejb.*;
import java.rmi.*;

public interface EmployeeLocalHome extends EJBLocalHome
{

  public EmployeeLocal create(Integer empNo) throws CreateException;

  // Find an existing employee
  public EmployeeLocal findByPrimaryKey (Integer empNo) throws FinderException;

  //Find all employees
  public Collection findAll() throws FinderException;

  //Calculate the Salaries of all employees
  public float calcSalary() throws Exception;
}

Implement the Entity Bean Component Interfaces

The entity bean component interfaces are the interfaces that the customer sees and invokes methods upon. The component interface defines the business logic methods for the entity bean instance.

  • The local component interface extends javax.ejb.EJBLocalObject.

  • The remote component interface extends javax.ejb.EJBObject.

The employee entity bean example exposes the local component interface, which contains methods for retrieving and updating employee information.

package employee;

import javax.ejb.*;

public interface EmployeeLocal extends EJBLocalObject
{
  public Integer getEmpNo();
  public void setEmpNo(Integer empNo);

  public String getEmpName();
  public void setEmpName(String empName);

  public Float getSalary();
  public void setSalary(Float salary);
}

Implement the Entity Bean Class

The entity bean class implements the following methods:

  • The target methods for the methods that are declared in the home interface, which include the following:

    • The ejbCreate and ejbPostCreate methods with parameters matching the associated create method defined in the home interface.

    • Finder methods, other than ejbFindByPrimaryKey and ejbFindAll, that are defined in the home interface. The container generates the ejbFindByPrimaryKey and ejbFindAll method implementations—although you must still provide an empty method for each of these.

    • any home interface business methods, which are prepended with ejbHome in the bean implementation. For example, the calcSalary method is implemented in the ejbHomeCalcSalary method.

  • The business logic methods that are declared in the component interfaces.

  • The methods that are inherited from the javax.ejb.EntityBean interface.

However, with container-managed persistence, the container manages most of the target methods and the data objects, thereby leaving little for you to implement.

package employee;

import javax.ejb.*;
import java.rmi.*;

public abstract class EmployeeBean implements EntityBean
{

  private EntityContext ctx;

  // Each CMP field has a get and set method as accessors
  public abstract Integer getEmpNo();
  public abstract void setEmpNo(Integer empNo);

  public abstract String getEmpName();
  public abstract void setEmpName(String empName);

  public abstract Float getSalary();
  public abstract void setSalary(Float salary);

  public void EmployeeBean()
  {
    // Constructor. Do not initialize anything in this method.
    // All initialization should be performed in the ejbCreate method.
    // The passivate() method may destroy these attributes when pooling
  }

  public float ejbHomeCalcSalary() throws Exception
  {
    Collection c = null;
    try {
       c = ((EmployeeLocalHome)this.ctx.getEJBLocalHome()).findAll();

       Iterator i = c.iterator();
       float totalSalary = 0;
       while (i.hasNext())
       {
         EmployeeLocal e = (EmployeeLocal)i.next();
         totalSalary = totalSalary + e.getSalary().floatValue();
       }
       return totalSalary;
    }
    catch (FinderException e) {
      System.out.println("Got finder Exception "+e.getMessage());
      throw new Exception(e.getMessage());
    }
  }

  public EmployeePK ejbCreate(Integer empNo, String empName, Float salary)
    throws CreateException
  {
    setEmpNo(empNo);
    setEmpName(empName);
    setSalary(salary);
    return new EmployeePK(empNo);
  }

  public void ejbPostCreate(Integer empNo, String empName, Float salary)
    throws CreateException
  {
    // Called just after bean created; container takes care of implementation
  }

  public void ejbStore()
  {
    // Called when bean persisted; container takes care of implementation
  }

  public void ejbLoad()
  {
     // Called when bean loaded; container takes care of implementation
  }

  public void ejbRemove() throws RemoveException
  {
     // Called when bean removed; container takes care of implementation
  }

  public void ejbActivate()
  {
    // Called when bean activated; container takes care of implementation.
    // If you need resources, retrieve them here.
  }

  public void ejbPassivate()
  {
    // Called when bean deactivated; container takes care of implementation.
    // if you set resources in ejbActivate, remove them here.
  }

  public void setEntityContext(EntityContext ctx)
  {
    this.ctx = ctx;
  }

  public void unsetEntityContext()
  {
    this.ctx = null;
  }
}

Note:

The entire CMP entity bean example (cmpapp.jar) is available on OTN from the OC4J sample code page at http://www.oracle.com/technology/tech/java/oc4j/demos/ on the OTN Web site.