Skip Headers
Oracle® Application Server Containers for J2EE Enterprise JavaBeans Developer's Guide
10g Release 2 (10.1.2)
Part No. B15505-02
  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
 

5 Entity Beans

This chapter demonstrates Entity Bean development with a basic configuration and deployment. Download the entity bean example from the OC4J sample code page at http://www.oracle.com/technology/tech/java/oc4j/demos/ on the OTN Web site.

This chapter demonstrates the following:

See Chapter 8, "BMP Entity Beans", for an example of how to create a simple bean-managed persistent entity bean. For a description of persisting object relationships between EJBs, see Chapter 6, "Entity Relationship Mapping".

Entity Bean Overview

With EJB 2.0 and the local interface support, most developers agree that entity beans should be paired with a session bean, servlet, or JSP that acts as the client interface. The entity bean is a coarse-grain bean that encapsulates functionality and represents data and dependent objects. Thus, you decouple the client from the data so that if the data changes, the client is not affected. For efficiency, the session bean, servlet, or JSP can be collocated with entity beans and can coordinate between multiple entity beans through their local interfaces. This is known as a session facade design. See the http://java.sun.com/ Web site for more information on session facade design.

An entity bean can aggregate objects together and effectively persist data and related objects under the umbrella of transactional, security, and concurrency support through the container. This and the following chapters focus on how to use the persistence functionality of the entity bean.

An entity bean manages persistent data in one of two ways: container-managed persistence (CMP) and bean-managed persistence (BMP). The primary difference between the two is as follows:

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 5-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.

How to Define and Use Primary Keys for Your Entity Bean

Each entity bean instance has a primary key that uniquely identifies it from other instances. You must declare the primary key (or the fields contained within a complex primary key) as a container-managed persistent field in the deployment descriptor. All fields within the primary key are restricted to either primitive, serializable, or types that can be mapped to SQL types. You can define your primary key in one of two ways:

For a simple CMP, you can define your primary key to be a well-known type by defining the data type of the primary key within the deployment descriptor.

The employee example defines its primary key as a java.lang.Integer and uses the employee number (empNo) as its primary key.

<enterprise-beans>
      <entity> 
         <display-name>Employee</display-name>
         <ejb-name>EmployeeBean</ejb-name>
         <local-home>employee.EmployeeLocalHome</local-home>
         <local>employee.EmployeeLocal</local>
         <ejb-class>employee.EmployeeBean</ejb-class>
         <persistence-type>Container</persistence-type>
         <prim-key-class>java.lang.Integer</prim-key-class>
         <reentrant>False</reentrant>
         <cmp-version>2.x</cmp-version>
         <abstract-schema-name>Employee</abstract-schema-name>
         <cmp-field><field-name>empNo</field-name></cmp-field>
         <cmp-field><field-name>empName</field-name></cmp-field>
         <cmp-field><field-name>salary</field-name></cmp-field>
        <primkey-field>empNo</primkey-field>
      </entity>
...
</enterprise-beans>

Once defined, the container creates a column in the entity bean table for the primary key and maps the primary key defined in the deployment descriptor to this column.


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.

Within the orion-ejb-jar.xml file, the primary key is mapped to the underlying database persistence storage by mapping the CMP field or primary key field defined in the ejb-jar.xml file to the database column name. In the following orion-ejb-jar.xml fragment, the EmpBean persistence storage is defined as the EMP table in the database that is defined in the jdbc/OracleDS data source. Following the <entity-deployment> element definition, the primary key, empNo, is mapped to the EMPNO column in the Emp table, and the empName and salary CMP fields are mapped to EMPNAME and SALARY columns respectively in the EMP table.

<entity-deployment name="EmpBean" ...table="EMP"                   data-source="jdbc/OracleDS"...   >
 <primkey-mapping>
  <cmp-field-mapping name="empNo" persistence-name="EMPNO" />
 </primkey-mapping>
 <cmp-field-mapping name="empName" persistence-name="EMPNAME" />
 <cmp-field-mapping name="salary" persistence-name="SALARY" />

Defining the Entity Bean Primary Key in a Class

If your primary key is more complex than a simple data type, your primary key must be a class that is serializable of the name <name>PK. You define the primary key class within the <prim-key-class> element in the deployment descriptor.

The primary key variables must adhere to the following:

  • Be defined within a <cmp-field><field-name> element in the deployment descriptor. This enables the container to manage the primary key fields.

  • Be declared within the bean class as public and restricted to be either primitive, serializable, or types that can be mapped to SQL types.

  • The names of the variables that make up the primary key must be the same in both the <cmp-field><field-name> elements and in the primary key class.

Within the primary key class, you implement a constructor for creating a primary key instance. Once the primary key class is defined in this manner, the container manages the class.

The following example places the employee number within a primary key class.

package employee;

public class EmployeePK implements java.io.Serializable
{
  public Integer empNo;

  public EmployeePK()
  {
    this.empNo = null;
  }

  public EmployeePK(Integer empNo)
  {
    this.empNo = empNo;
  }
}

The primary key class is declared within the <prim-key-class> element, and each of its variables are declared within a <cmp-field><field-name> element in the XML deployment descriptor, as follows:

<enterprise-beans>
      <entity>
         <description>no description</description>
         <display-name>EmployeeBean</display-name>
         <ejb-name>EmployeeBean</ejb-name>
         <local-home>employee.LocalEmployeeHome</home>
         <local>employee.LocalEmployee</remote>
         <ejb-class>employee.EmployeeBean</ejb-class>
         <persistence-type>Container</persistence-type>
        <prim-key-class>employee.EmployeePK</prim-key-class>
         <reentrant>False</reentrant>
         <cmp-version>2.x</cmp-version>
         <abstract-schema-name>Employee</abstract-schema-name>
        <cmp-field><field-name>empNo</field-name></cmp-field>
         <cmp-field><field-name>empName</field-name></cmp-field>
         <cmp-field><field-name>salary</field-name></cmp-field>
      </entity>
</enterprise-beans>

Once defined, the container creates a column in the entity bean table for the primary key and maps the primary key class defined in the deployment descriptor to this column.

The CMP fields are mapped in the orion-ejb-jar.xml in the same manner as described in "How to Define and Use Primary Keys for Your Entity Bean". With a complex primary key, the mapping contains more than a single field; thus, the <cmp-field-mapping> element of the <primkey-mapping> element contains another subelement: the <fields> element. All of the fields of a primary key are each defined in a separate <cmp-field-mapping> element within the <fields> element, as shown below.

<primkey-mapping>
 <cmp-field-mapping>
   <fields>
    <cmp-field-mapping name="empNo" persistence-name="EMPNO" />
   </fields>
 </cmp-field-mapping>
</primkey-mapping>

Special mapping needs to happen if you have a complex primary key that contains a foreign key. See "Using a Foreign Key in a Composite Primary Key" for directions.

Defining an Auto-Generated Primary Key for Your Entity Bean

If you specify a java.lang.Object as the primary key class type in <prim-key-class>, but do not specify the primary key name in <primkey-field>, then the primary key is auto-generated by the container.

The employee example defines its primary key as a java.lang.Object. Thus, the container auto-generates the primary key.

<enterprise-beans>
      <entity> 
         <display-name>Employee</display-name>
         <ejb-name>EmployeeBean</ejb-name>
         <local-home>employee.EmployeeLocalHome</local-home>
         <local>employee.EmployeeLocal</local>
         <ejb-class>employee.EmployeeBean</ejb-class>
         <persistence-type>Container</persistence-type>
         <prim-key-class>java.lang.Object</prim-key-class>
         <reentrant>False</reentrant>
         <cmp-version>2.x</cmp-version>
         <abstract-schema-name>Employee</abstract-schema-name>
         <cmp-field><field-name>empNo</field-name></cmp-field>
         <cmp-field><field-name>empName</field-name></cmp-field>
         <cmp-field><field-name>salary</field-name></cmp-field>
      </entity>
...
</enterprise-beans>

Once defined, the container creates a column called autoid in the entity bean table for the primary key of type LONG. The container uses random numbers for the primary key values. This is generated in the orion-ejb-jar.xml for the bean, as follows:

<primkey-mapping>
  <cmp-field-mapping name="auto_id" 
         persistence-name="autoid"/>
</primkey-mapping>

Create Data Consistency in Your Entity Bean by Using Persistence

There are two methods for managing the persistent data within an entity bean: bean-managed (BMP) and container-managed persistence (CMP). The main difference between BMP and CMP beans is defined by who manages the persistence of the entity bean's data. With CMP beans, the container manages the persistence—the bean deployment descriptor specifies how to map the data and where the data is stored. With BMP beans, the logic for saving the data and where it is saved is programmed within designated methods. These methods are invoked by the container at the appropriate moments.

In practical terms, the following table provides a definition for both types, and a summary of the programmatic and declarative differences between them:

Management Issues Bean-Managed Persistence Container-Managed Persistence
Persistence management You are required to implement the persistence management within the ejbStore, ejbLoad, ejbCreate, and ejbRemove EntityBean methods. These methods must contain logic for saving and restoring the persistent data.

For example, the ejbStore method must have logic in it to store the entity bean's data to the appropriate database. If it does not, the data can be lost.

The management of the persistent data is done for you. That is, the container invokes a persistence manager on behalf of your bean.

You use ejbStore and ejbLoad for preparing the data before the commit or for manipulating the data after it is refreshed from the database. The container always invokes the ejbStore method right before the commit. In addition, it always invokes the ejbLoad method right after reinstating CMP data from the database.

Finder methods allowed The findByPrimaryKey method and other finder methods are allowed. The findByPrimaryKey method and other finder methods clause are allowed.
Defining CMP fields N/A Required within the EJB deployment descriptor. The primary key must also be declared as a CMP field.
Mapping CMP fields to resource destination N/A Required. Dependent on persistence manager.
Definition of persistence manager N/A Required within the Oracle-specific deployment descriptor. See the next section for a description of a persistence manager.

For more information on container-managed persistence, see Chapter 4, "CMP Entity Beans"; for information on bean-managed persistence, see Chapter 8, "BMP Entity Beans".

Tie Entity Beans Together Through Container-Managed Relationships

The EJB 2.0 specification enables the specification of relationships between entity beans. An entity bean can be defined so as to have a relationship with other entity beans. You implement relationships differently for entity beans with bean-managed-persistence than those entity beans that utilize container-managed-persistence. With bean-managed persistence, the code that you write implements the relationships. With container-managed persistence, the EJB container takes care of the relationships for you. For this reason, relationships in entity beans with container-managed persistence are often referred to as container-managed relationships.

For more information, see Chapter 4, "CMP Entity Beans" for container-managed persistence, Chapter 6, "Entity Relationship Mapping" for CMR relationships, and Chapter 7, "EJB Query Language" for EJB QL.

Managing the Entity Bean Lifecycle

You can manage the entity bean lifecycle through configuring pool sizes for your entity beans. This subject is covered in the following section:

Configuring Pool Sizes For Entity Beans

You can set the minimum and maximum number of the bean instance pool, which contains EJB implementation instances that currently do not have assigned state. While the bean instance is in pool state, it is generic and can be assigned to a wrapper instance.

You can set the pool number with the following attributes of the <entity-deployment> element.

  • The max-instances attribute sets the maximum entity bean instances to be allowed in the pool. An entity bean is set to a pooled state if not associated with a wrapper instance. Thus, it is generic.

    The default is 0, which means infinite. If you wanted to set the maximum bean implementation instances to 20, you would do as follows:

    <entity-deployment ...  max-instances="20"
     ...
    </entity-deployment>
    
    
  • The min-instances attribute sets the minimum number allowed in the pool as follows:

    <entity-deployment ... min-instances="2"
     ...
    </entity-deployment>
    

How to Avoid Database Resource Contention

In order to avoid resource contention and overwriting each others changes to database tables while allowing concurrent execution, entity bean concurrency and database isolation modes are provided.

Using Database Isolation Modes to Protect Against Resource Contention

The java.sql.Connection object represents a connection to a specific database. Database isolation modes are provided to define protection against resource contention. When two or more users try to update the same resource, a lost update can occur. That is, one user can overwrite the other user's data without realizing it. The java.sql.Connection standard provides four isolation modes, of which Oracle only supports two of these modes. These are as follows:

  • TRANSACTION_READ_COMMITTED: Dirty reads are prevented; non-repeatable reads and phantom reads can occur. This level only prohibits a transaction from reading a row with uncommitted changes in it.

  • TRANSACTION_SERIALIZABLE: Dirty reads, non-repeatable reads and phantom reads are prevented. This level includes the prohibitions in TRANSACTION_REPEATABLE_READ and further prohibits the situation where one transaction reads all rows that satisfy a WHERE condition, a second transaction inserts a row that satisfies that WHERE condition, and the first transaction rereads for the same condition, retrieving the additional "phantom" row in the second read.


    Note:

    You cannot set the isolation level to serializable if you are using a non-emulated data source. If you do, the non-emulated data source will not work.

You can configure one of these database isolation modes for a specific bean. That is, you can specify that when the bean starts a transaction, the database isolation mode for this bean be what is specified in the OC4J-specific deployment descriptor. Specify the isolation mode on what is important for the bean: parallel execution or data consistency. The isolation mode for this bean is set for the entire transaction.

The isolation mode can be set for each entity bean in the isolation attribute of the <entity-deployment> element. The values can be committed or serializable. The default is committed. To change it to serializable, configure the following in the orion-ejb-jar.xml for the intended bean:

<entity-deployment ...  isolation="serializable"
 ...
</entity-deployment>

There is always a trade-off between performance and data consistency. The serializable isolation mode provides data consistency; the committed isolation mode provides for parallel execution.


Note:

There is a danger of lost updates with the serializable mode if the max-tx-retries element in the OC4J-specific deployment descriptor is greater than zero. The default for this value is zero. If this element is set to greater than zero, then the container retries the update if a second blocked client receives a ORA-8177 exception. The retry would find the row unlocked and the update would occur. Thus, the second client's update succeeds and overwrites the first client's update. If you use serializable, you should consider leaving the max-tx-retries element as zero for data consistency.

If you do not set an isolation mode, you receive the mode that is configured in the database. Setting the isolation mode within the OC4J-specific deployment descriptor temporarily overrides the database configured isolation mode for the life of the global transaction for this bean. That is, if you define the bean to use the serializable mode, then the OC4J container will force the database to be serializable for this bean only until the end of the transaction.

You can specify both entity bean concurrency modes and database isolation modes, where the combination effects the outcome of your resource contention. See "Effects of the Combination of the Database Isolation and Bean Concurrency Modes" for more information.

Configuring Entity Bean Concurrency Modes For Handling Resource Contention

OC4J also provides concurrency modes for handling resource contention and parallel execution within container-managed persistence (CMP) entity beans. Bean-managed persistence entity beans manage the resource locking within the bean implementation themselves. The concurrency modes configure when to block to manage resource contention or when to execute in parallel.

The concurrency modes are as follows:

  • PESSIMISTIC: This manages resource contention and does not allow parallel execution. Only one user at a time is allowed to execute the entity bean at a single time.

  • OPTIMISTIC: Multiple users can execute the entity bean in parallel. It does not monitor resource contention; thus, the burden of the data consistency is placed on the database isolation modes.

  • READ-ONLY: Multiple users can execute the entity bean in parallel. The container does not allow any updates to the bean's state.

To enable the CMP entity bean concurrency mode, add the appropriate concurrency value of "pessimistic", "optimistic", or "read-only" to the locking-mode attribute of the <entity-deployment> element in the OC4J-specific deployment descriptor (orion-ejb-jar.xml). The default is "optimistic". To modify the concurrency mode to pessimistic, do the following:

<entity-deployment ...  locking-mode="pessimistic"
 ...
</entity-deployment>

These concurrency modes are defined per bean and the effects of locking apply on the transaction boundaries.

Parallel execution requires that the pool size for wrapper and bean instances are set correctly. For more information on how to configure the pool sizes, see "Configuring Environment References".

You can specify both entity bean concurrency modes and database isolation modes, where the combination effects the outcome of your resource contention. See "Effects of the Combination of the Database Isolation and Bean Concurrency Modes" for more information.

Specifying Exclusive Write Access to the Database

The exclusive-write-access attribute of the <entity-deployment> element states that this is the only bean that accesses its table in the database and that no external methods are used to update the resource. It informs the OC4J instance that any cache maintained for this bean will only be dirtied by this bean. Essentially, if you set this attribute to true, you are assuring the container that this is the only bean that will update the tables used within this bean. Thus, any cache maintained for the bean does not need to constantly update from the back-end database.

This flag does not prevent you from updating the table; that is, it does not actually lock the table. However, if you update the table from another bean or manually, the results are not automatically updated within this bean.

The default for this attribute is false. Because of the effects of the entity bean concurrency modes, this element is only allowed to be set to true for a read-only entity bean. OC4J will always reset this attribute to false for pessimistic and optimistic concurrency modes.

<entity-deployment ...  exclusive-write-access="true"
 ...
</entity-deployment>

Effects of the Combination of the Database Isolation and Bean Concurrency Modes

For the pessimistic and read-only concurrency modes, the setting of the database isolation mode does not matter. These isolation modes only matter if an external source is modifying the database.

If you choose optimistic with committed, you have the potential to lose an update. If you choose optimistic with serializable, you will never lose an update. Thus, your data will always be consistent. However, you can receive an ORA-8177 exception as a resource contention error.

Differences Between Pessimistic and Optimistic/Serializable

An entity bean with the pessimistic concurrency mode does not allow multiple clients to execute a bean (either on the same or on different instances of the same primary key). Only one client is allowed to execute the instance at any one moment.

An entity bean with the optimistic concurrency mode allows multiple instances of the bean implementation to execute in parallel. However, it could result in potential lost updates (and conflicts), because two different transactions may update the same row simultaneously.

Setting the transaction isolation mode to serializable allows the detection of conflicts when they occur. At that moment, the update from one of the transactions raises a SQLException and that transaction is rolled back.

Optionally, you may set the tx-retries attribute of the <entity-deployment> element to a value more than one, so that the transaction is retried.

Affects of Concurrency Modes on Clustering

All concurrency modes behave in a similar manner whether they are used within a standalone or a clustered environment. This is because the concurrency modes are locked at the database level. Thus, even if a pessimistic bean instance is clustered across nodes, the moment one instance tries to execute, the database locks out all other instances.

Using Transactions With Entity Beans

All entity beans with CMP and CMR relationships must be involved in a transaction. As such, you cannot define any entity bean with a transaction attribute of NEVER, SUPPORTS, or NOT_REQUIRED as this would put the entity outside of a transaction.

For more information on how to use, configure, and manage transactions for entity beans, see the JTA chapter in the Oracle Application Server Containers for J2EE Services Guide.

Providing Security for Your Entity Beans

OC4J provides security for your entity beans—whether you are interested in Java2 security or OracleAS JAAS Provider. However, you still have to configure the type of security that you desire. For more information, see the Oracle Application Server Containers for J2EE Security Guide.