On Tue, 27 Feb 2001 10:19:14 -0800, Cedric Beust
<[EMAIL PROTECTED]> wrote:

>> From: A mailing list for Enterprise JavaBeans development
>> [mailto:[EMAIL PROTECTED]]On Behalf Of Satyabrata Dash
>
>> I believe that we override hashcode() to ensure same hashcode for the same
>> primary key everytime the container calls it. It is essential because each
>> entity bean maps to a single row in database. So it is essential that the
>> same primary key is evaluated to same hashcode everytime. Container maintains
>> the identity of the entity bean in a hashtable where hashcode and primary key
>> are key, value pairs. that is ensured by overriding the hashcode() method.
>> Again we override equals() method to find out whether the primary key is same
>> or not.
>
>Technically, you don't *have* to override hashCode().  The default Object
>implementation will work fine.

Probaby not always. Suppose in my client code I want to cache copies
of entity bean remote interfaces in a Hashtable, with their primary
key objects as the lookup key. When I want to retrieve a remote
interface from the Hashtable, unless I use the exact same physical PK
object as the lookup key, the Hashtable.get(Object key) method will
fail. That's because the hashCode() value returned by Object's
implementation will be virtually unique for every object within a JVM,
and the Object class's .equals(Object other) method only returns true
if both references point to the exact same object in memory. As the
API for the Object class says:

"The equals method for class Object implements the most discriminating
possible equivalence relation on objects; that is, for any reference
values x and y, this method returns true if and only if x and y refer
to the same object (x==y has the value true)."

You should always implement hashCode() and equals() in your primary
key class in a way so that if two primary key objects belong to the
same Entity (i.e. database row), then their hashCode() will return
identical values, and object1.equals(object2) will return true. The
"correct" way to implement hashCode() and equals() are described in
the API for the Object class at:

http://java.sun.com/j2se/1.3/docs/api/java/lang/Object.html#hashCode()

http://java.sun.com/j2se/1.3/docs/api/java/lang/Object.html#equals(java.lang.Object)

The EJB 1.1 spec seems to support this. In 9.2.9 it says:

"The [entity bean's primary key] class must provide suitable
implementation of the hashCode() and equal(Object other) methods to
simplify the management of the primary keys by client code."

===========================================================================
To unsubscribe, send email to [EMAIL PROTECTED] and include in the body
of the message "signoff EJB-INTEREST".  For general help, send email to
[EMAIL PROTECTED] and include in the body of the message "help".

Reply via email to