Bean Managed Persistence   «Prev  Next»

Lesson 5 Finding by primary key
ObjectiveUse the primary key to find a persistent entity.

Finding by primary key

The home interface has a method findByPrimaryKey(PrimaryKey).
This method takes a primary key object and returns the EJBObject reference to instance representing the entity object.
The client code uses the EJBObject reference to access the bean instance. The client code is as follows:

public Customer findByPrimaryKey(String  primaryKey) 

throws  FinderException, RemoteException;

The home object grabs an instance from the pool and invokes the
ejbFindByPrimaryKey(PrimaryKey).

This method uses the primary key to find the entity object and synchronize it with the instance. This method returns the primary key of the newly found entity object to the container. The container creates the EJBObject and passes its reference back to the home object. The MouseOver below explains the code for the ejbFindByPrimaryKey():

find-by-primary-key
  1. The ejbFindByPrimaryKey() is invoked by the container when the home interface findByPrimaryKey() is invoked.
  2. selectByPrimaryKey() invokes the JDBC code to find the row using the information in the primary key. It returns true if the row is found, otherwise it returns false.
  3. A row was found, so it returns the primary key to the container.
  4. No row was found, so it return the ObjectNotFoundException to the client.
  5. If any exception is thrown by the JDBC code, it is caught and the EJBException is returned to the client. Notice that any message contained in the caught exception is passed back in the EJBException.

finding By Primary Key

Finding rows

There are other kinds of finder methods that can be used to locate one or more entity objects in the database. These are discussed in a later module.

Finding Entity Objects Quiz

Click the Quiz link below to review your understanding of creating and finding entity beans.
Finding Entity Objects - Quiz
The next lesson examines the EJBObject for the entity bean.