# The Life Cycle of an Entity Bean

The following figure shows the life cycle of an entity bean. An entity bean has the following three states:

- Does Not Exist. In this state, the bean instance simply does not exist.
- Pooled. When WebLogic server is first started, several bean instances are created and placed in the pool. A bean instance in the pooled state is not tied to particular data, that is, it does not correspond to a record in a database table. Additional bean instances can be added to the pool as needed, and a maximum number of instances can be set (for more information, see the @ejbgen:entity Annotation).
- Ready. A bean instance in the ready state is tied to particular data, that is, it represents an instance of an actual business object.

The various state transitions as well as the methods available during the various states are discussed below.

## Moving from the Does Not Exist to the Pooled State

When WebLogic server creates a bean instance in the pool, it calls the callback method public void setEntityContext(EntityContext ctx). This method has the parameter javax.ejb.EntityContext, which contains a reference to the entity context, that is, the interface to the EJB container. The entity context contains a number of methods to self-reference the entity bean object, identify the caller of a method, and so forth. Complete details about the javax.ejb.EntityContext can be found in your favorite J2EE documentation and the API reference at http://java.sun.com.

If you want to use the EntityContext reference in the entity bean, you must implement this callback method and store the reference. In addition, this method is also frequently used to look up the home interface of other beans later invoked in one of the bean's methods. The following code sample shows both:

    /**
     * @ejbgen:ejb-local-ref link="Recording"
     *
     * ...
     */
    abstract public class BandBean extends GenericEntityBean implements EntityBean
    {
      private EntityContext ctx;
      private RecordingHome recordingHome;

      public void setEntityContext(EntityContext c) {
          // store the reference to the EntityContext
          ctx = c;
    		// look up the home interface of the RecordingBean
          try {
             javax.naming.Context ic = new InitialContext();
             recordingHome = (RecordingHome)ic.lookup("java:/comp/env/ejb/Recording");
          }
          catch(Exception e) {
             System.out.println("Unable to obtain RecordingHome: " + e.getMessage());
          }
      }

      ...

## The Pooled State

When a bean instance is in the pooled state, it is not tied to any particular business object. When in the pooled state, the methods defined in the home interface can be invoked, effectively transitioning it from the pooled to the ready state, with the exception of ejbHome methods. When a home method is invoked, a result that is not bean instance specific is returned to the caller, and the bean instance remains in the pooled state. Home methods in turn often invoke ejbSelect methods to query bean instances. For more information, see the Home Methods Sample.

## Moving from the Pooled to the Ready State

The following methods move a bean instance from the pooled to the ready state to represent a business object:

- ejbCreate and ejbPostCreate. When the create method is invoked on the bean's home interface, the ejbCreate and ejbPostCreate methods are invoked. The bean instance moves to the ready state and represents this newly created business object. After creation, a (local or remote) reference to this object is returned to the caller, enabling the caller to invoke business methods on this instance. The ejbPostCreate method is used to set references to other entity beans as part of the creation of a new bean instance. For more information, see Entity Relationships.
- findByPrimaryKey. When this method is invoked on the bean's home interface with the (compound) primary key as the parameter, the bean instance moves to the ready state and represents the business object uniquely identified by the parameter. Also a (local or remote) reference to this object is returned to the caller, enabling the caller to invoke business methods on this instance.
- Finder methods. When a Finder method is invoked on the bean's home interface, one or a set of references to objects matching the queries are returned to the caller. In many cases the corresponding bean instance(s) are not loaded with data and move to the ready state until at a later point when a business method is actually invoked on this object, a concept known as lazy loading. However, you can specify eager loading, that is, tell the EJB container to load (part of) the data and move the entity bean instance(s) to the ready state as a part of the finder method execution. For more information, see Accelerating Entity Bean Data Access.

## The Ready State

When a bean instance is in the ready state, it represent data for a business object. At this point any business method, that is any component method and accessor method, can be invoked on this object. (A component method may in turn call an ejbSelect method.) After a business method executes, the bean returns to the ready state to allow another business method invocation.

From the perspective of the EJB container, the execution of a component method is sandwiched between two synchronization steps:

1. Before a business method is executed, the EJB container updates the fields of the bean instance with the latest data from the database table to ensure that the bean instance has the latest data. Just after the data is updated, the EJB container invokes the callback method ejbLoad. If your entity bean needs to execute some custom logic as part of this synchronization step, you can use implement it using this callback method.
2. The business method executes and completes.
3. The EJB container now updates the database table to ensure that it contains the latest data from the entity bean instance. In other words, if the business method changes data values, this synchronization step ensures these changes are stored. Just prior to updating the database table, the EJB container invokes the callback method ejbStore. If your entity bean needs to execute some custom logic as part of this synchronization step, you can implement it using this callback method.

Because a record in a database table can be accessed by multiple bean instances at the same time, these synchronization steps ensure that each bean instance always has the latest data. However, in some cases these synchronization steps might be overkill and unnecessarily slow down performance. For instance, an entity bean might be read-only, reading data that is changed rarely if at all. In these cases one can safely bypass the synchronization steps without risking violations to data integrity. For more information, see Accelerating Entity Bean Data Access.

## Moving from the Ready to the Pooled State

When a caller invokes a remove method to delete an entity bean instance and its underlying record in the database table, the EJB container will delete the bean instance. Just prior to deleting the instance, it will call the callback method ejbRemove. If your entity bean needs to execute some custom logic prior to deletion, you can implement it using this callback method. After the data is deleted, the bean instance returns to the pooled state. The bean instance is no longer tied to any particular business object, and can be used to execute a home method or one of the methods that will tie it to a new set of data and move it to the ready state.

For more information on how to delete an entity bean instance, see Defining an Entity Bean.

## Activation and Passivation

To more optimally manage resources, the EJB container might passivate a bean instance by moving it from the ready state to the pooled state. During passivation the entity bean instance is dissociated from the business object it represents, and become available to represent another set of data. Conversely, a passivated bean might be activated, meaning that it moves from the pooled to ready state to represent a business object.

It should be noted that the caller (a client application or another EJB) of the entity bean instance will be unaware of passivation having taken place. The caller's reference to the entity bean instance is still maintained and valid; that is, if the caller subsequently invokes a business method on this entity bean instance, an instance from the pooled state will be moved to the ready state to represent this business object.

A bean instance can be passivated when none of its business method are invoked. Passivation occurs after synchronization has completed, guaranteeing that the database has stored any changes to the business object. Just prior to actual passivation, the callback method ejbPassivate is invoked. If your entity bean needs to execute some custom logic prior to passivation, you can implement it using this callback method.

When a previously passivated bean instance is activated to service business method invocation, the callback method ejbActivate is invoked. If your entity bean needs to execute some custom logic prior to activation, you can implement it using this callback method. For instance, you might use this callback method to reinitialize values of nonpersistent fields, that is, fields not stored in the database. After the callback method executes and completes, the synchronization - business method invocation - synchronization procedure described above follows as during any other business method invocation; that is, first synchronization happens during which the latest bean instance is updated with the latest data of the database, followed by the invocation of the ejbLoad callback method. After this completes the business method is invoked, and when this completes, the second synchronization happens during which the ejbStore callback method is invoked and the latest bean instance data is stored to the database.

## Moving from the Pooled to the Does Not Exist State

To more optimally manage resources, or when WebLogic server shuts down, the EJB container might remove a bean instance from the pooled state to the does not exist state, allowing it to be garbage collected. Just prior to its destruction, the callback method unsetEntityContext is invoked. If your entity bean needs to execute some cleanup prior to garbage collection, you can implement it using this callback method.

Related Topics

Accelerating Entity Bean Data Access

Entity Relationships