Originally posted by andy armstrong:
Just to confirm there have been a lot of places
in the notes where people have said you must
implement these functions for your primary key.
This is not the case!! You in fact should but it is not a must. You must have a no-arg constructor..
As well you should not even use the equals method
to determine equality but the isIdentical method.
Any comments..
Quoting from the
EJB Specification 2.0:
"10.6.13 Entity bean?s primary key class
The Bean Provider must specify a primary key class in the deployment descriptor.
The primary key type must be a legal Value Type in RMI-IIOP.
The class must provide suitable implementation of the hashCode() and equals(Object
other) methods to simplify the management of the primary keys by the Container."
So definitely you have to provide the implementation of the equals (Object) and hashCode() for your Primary Key class. Of course, if you use e.g. java.lang.String for your PK, that two methods are already implemented in a suitable way.
That is not surprisingly, since the default implementation of the equals(Object) method (inherithed from java.lang.Object) is to compare the "this" references of the two objects, so two PK objects with identical values would be always different (!) ...
Try this:
So you won't find your PK in an array even if it's there, even if you use the straighforward method of looping on the array comparing each element to your PK with the equals method - a thing that any client, not to mention the container, would definitely think it's safe to do.
This is much better:
Similar considerations apply for hashCode(); if you don't implement it correctly, you will have surprising results (such as adding your PK to a Collection and not finding it in the Collection immediately afterwards - even if it's there ...).
A *GREAT* dissertation on the subject is contained in "Effective Java" by Joshua Bloch, the best book on robust
Java Programming that I've ever read.