J2EEOnline J2EE

Entity Beans  «Prev  Next»
Lesson 3Finding an entity bean using its primary key
ObjectiveWrite the code to find an entity bean using its primary key.

Finding an Entity bean using its Primary Key

In this lesson you will find an existing entity object from the Customer database using its primary key.

Primary key

Each entity from the persistence store can be represented by an entity bean. Each entity must have, by definition, a primary key.
The primary key will be one or more variables that map to the data.
The home interface has a single method named findByPrimaryKey() as follows:

public Customer findByPrimaryKey
(String  primaryKey) throws    

The argument to this method is a class that represents the data for the primary key for a specific entity in the persistent store. The arguments to findByPrimaryKey() must be RMI IIOP compatible. In essence, this means that they must implement java.io.Serializable, implement the boolean equals(Object) and int hashCode() methods, and have a single no-arg constructor. All the variables in the class must be public. You will find that all the Java-based data types are RMI IIOP compliant.
findByPrimaryKey() returns the remote interface to the EJBObject of the instance. It must be public and throw Finder and Remote exceptions. As you will see later, for bean-managed persistence, findByPrimaryKey() maps to the ejbFindByPrimaryKey() method in the bean. This structure is similar to session beans.

The client side

The client uses the findByPrimaryKey() of the home interface to find a particular entity.
If the entity exists, the container creates a bean instance for the data, creates the EJBObject, and returns the reference to it. Subsequently, the methods of the bean can be called. The code in the Customer client is as follows:

Customer bean1 = home.findByPrimaryKey("333");

Notice that the primary key in this example is a java.lang.String and the return is the remote reference.
The next lesson introduces the business and the remove methods.