Prev | Next

TOC | Index

J2EETM Developer's Guide
Entity Beans

The Life Cycle of an Entity Bean

The life cycle of an entity bean is controlled by the EJB container, not by your application. However, you may find it helpful to learn about the life cycle when deciding in which method your entity bean will connect to a database. (See the Database Connections chapter for more information.)

Figure 4-1 shows the stages that an entity bean passes through during its lifetime. After the EJB container creates the instance, it calls the setEntityContext method of the entity bean class. The setEntityContext method passes the entity context to the bean.

After instantiation, the entity bean moves to a pool of available instances. While in the pooled stage, the instance is not associated with any particular EJB object identity. All instances in the pool are identical. The EJB container assigns an identity to an instance when moving it to the ready stage.

There are two paths from the pooled stage to the ready stage. On the first path, the client invokes the create method, causing the EJB container to call the ejbCreate and ejbPostCreate methods. On the second path, the EJB container invokes the ejbActivate method. While in the ready stage, an entity bean's business methods may be invoked.

There are also two paths from the ready stage to the pooled stage. First, a client may invoke the remove method, which causes the EJB container to call the ejbRemove method. Second, the EJB container may invoke the ejbPassivate method.

At the end of the life cycle, the EJB container removes the instance from the pool and invokes the unsetEntityContext method.

FIGURE 4-1 Life Cycle of an Entity Bean

In the pooled state, an instance is not associated with any particular EJB object identity. With bean-managed persistence, when the EJB container moves an instance from the pooled state to the ready state, it does not automatically set the primary key. Therefore, the ejbCreate and ejbActivate methods must set the primary key. If the primary key is incorrect, the ejbLoad and ejbStore methods cannot synchronize the instance variables with the database. In the AccountEJB example, the ejbCreate method assigns the primary key from one of the input parameters. The ejbActivate method sets the primary key (id) as follows:

id = (String)context.getPrimaryKey();
In the pooled state, the values of the instance variables are not needed. You can make these instance variables eligible for garbage collection by setting them to null in the ejbPasssivate method.

Prev | Next

TOC | Index

Copyright © 2000 Sun Microsystems, Inc. All rights reserved.