Bean Managed Persistence   «Prev  Next»

Lesson 8Entity bean container callbacks:
ObjectiveReview the code for the ejbLoad() and ejbStore() methods.

ejbLoad() and ejbStore()

ejbLoad() method

The ejbLoad() method is called by the container when the data belonging to the persistent entity must be loaded into the bean instance. Following the method call, the state of the bean instance is synchronized with the underlying entity object and the bean's existing internal state is discarded. It is the bean developer's responsibility to provide the code in the ejbLoad() method that loads the data. The ejbLoad() for the Customer bean is as follows:
public void ejbLoad() {
 try {
  loadRow();
 } catch (Exception e) {
 throw new EJBException("ejbLoad: " + 
  e.getMessage());
 }
}

In the Customer bean, loadRow() invokes JDBC code to load the row. It uses the data drawn from the instance variables of the bean instance to create the primary key. Using the primary key, it populates the non-primary key variables in the instance. This means that the primary key variables must be set before ejbLoad() is invoked.

ejbStore() method

The ejbStore() method is the reverse of ejbLoad(). It stores the data from the instance variables into the entity object. The container invokes this method when the data has to be stored. The code for the Customer ejbLoad() is:
public void ejbStore() {
 try {
  storeRow();
 } catch (Exception e) {
  throw new EJBException("ejbLoad: " + 
  e.getMessage());
 }
}

When does the container invoke these methods?

Even though this is bean-managed persistence, it is the container's responsibility to invoke these methods. When does this happen? The begin and commit transaction requests trigger the container to store or load the entity. Both ejbStore() and ejbLoad() methods are invoked in the transaction context of the method that triggered them. Usually, the load happens at the start of the transaction, just before the business method is executed. The store happens when the container is notified by the transaction service that a commit has been requested, and just before the commit actually takes place.
Warning: Within container-managed transactions, if you do not invoke the business methods within a transaction context, there is no way the container knows to invoke the ejbStore() method and, thus, the persistent entity object will not be updated. The next lesson examines the ejbActivate(), ejbPassivate() , and ejbRemove() callbacks.