Entity bean container callbacks: ejbActivate() and ejbPassivate()
Objective
Learn the code for the entity bean container callbacks: ejbActivate() and ejbPassivate().
Entity bean Container Callbacks
ejbActivate()
When the container needs a bean instance to service a client's request on a specific EJBObject, it takes an instance from the
pool and associates it with the specific entity object identity associated with the EJBObject, then it invokes its
setEntityContext() method. For this to happen, there must have been a prior create() or
findByPrimaryKey() method invoked by the client that created the EJBObject.
That's because, in the container, every EJBObject is associated with an existing entity object identity.
The ejbActivate() method allows the entity bean instance to acquire additional resources that are needed in the ready
state. For example, the primary key instance variables must be initialized. This is required so that the ejbLoad()
method is able to execute successfully.
After ejbActivate() is called, the primary key, the entity object identity, and the EJBObject remain associated with
the bean instance until either the completion of ejbPassivate() or the completion of ejbRemove()methods. This
is a long explanation for what turns about to be a small amount of code. For the Customer bean the code is as follows:
public void ejbActivate() {
// initialize the primary key fields from the
EntityContext custnum = (String) context.getPrimaryKey();
// initialize any resources here
}
Notice that the primary key is retrieved from the instance's context and used to initialize the primary key variables.
ejbPassivate()
The ejbPassivate() method is called when the instance is being put back in the pool. At that time the container
disassociates the instance from the object identity. Notice that passivate does not write the object to secondary
storage as occurs with session beans. This is because the instance and the underlying persistent entity object are synchronized
at the beginning of any transaction by loading the data. It is simpler to grab an instance from the pool, associate it with the
EJBObject, and then invoke ejbLoad(). The code for ejbPassivate() method is very simple:
public void ejbPassivate() {
custnum = null;
// release any resources
}
The image below illustrates the object interactions during activation and passivation.
The next lesson introduces the ejbRemove() method.