Entity Beans   «Prev  Next»

Lesson 4The primary key and object identity
ObjectiveDescribe how to use the primary key/compare identity of entity bean.

Primary Key and Object Identity

Unique identity

Every entity bean has a unique identity within its home. This identity, known as the primary key, relates directly to the underlying data. Entity beans can be looked up by their clients using this primary key. The primary key identifies the entity bean within its home. Two beans in different containers (different homes) may have the same primary key. This feature allows load balancing between multiple containers that contain multiple entity beans that represent the same underlying data.

The Identity rule for Entity Beans

If two entity bean instances have the same home object and the same primary key, then they are the same instance.

Primary key format

The developer of the bean creates the primary key. It will have instance variables that are appropriate for storing the values that represent the primary key. The key is tightly coupled to the bean it represents. It must be a legal RMI-IIOP type, which means that it is serializable at the very least. The following MouseOver explains the structure of a primary key.

  1. The primary key class is serializable. It can have any name. It helps to use the format of <name>PK.class as this fits in with <name>Home, etc
  2. This primary key is for a customer number that is represented by a single int.
  3. The constructor is used to initialize the instance variables, custNum in this case
  4. It is very important that the primary key contains an equal() method that can be used to compare two primary keys for equality.
  5. In this case we compare if they are the same object.
  6. If they are not the same object, then we compare them for equality. Primary keys that have the same value refer to the same persistent object by definition.
  7. If neither of the above are true we return false to indicate inequality.
  8. A primary key must implement the hashCode() method.

Primary Key Class

Retrieving the primary key

The EJBObject has a method that will always return the current primary key for its specific entity bean instance. This requires that the bean instance already be accessible to the client.

Object getPrimaryKey ()
The primary key is returned as a Java object that must be cast to the appropriate type. For example:
CustomerPK myKey = (CustomerPK) bean.getPrimaryKey();

The next lesson introduces the code used to look up a bean using its primary key.