Chapter 15. Design Strategies
The previous 14 chapters have presented the core EJB technology. What’s left is a grab bag of miscellaneous issues: how to solve particular design problems, how to work with particular kinds of databases, and topics of that nature.
Hash Codes in Compound Primary Keys
Chapter 11
discusses the necessity of overriding the
Object.hashCode() and
Object.equals() methods in the primary key class
of an entity bean. With complex primary keys that have several
fields, overriding Object.equals() is fairly
trivial. However, overriding
Object.hashCode()
is more
complicated, because an integer value that can serve as a suitable
hash code must be created from several fields.
One solution is to concatenate all the values into a
String and use the String
object’s hashCode() method to create a hash
code value for the whole primary key. The String
class has a decent hash code algorithm that generates a fairly
well-distributed and repeatable hash code value from any set of
characters.
The following code shows how to create such a hash code for a hypothetical primary key:
public class HypotheticalPrimaryKey implements java.io.Serializable { public int primary_id; public short secondary_id; public java.util.Date date; public String desc; public int hashCode() { StringBuffer strBuff = new StringBuffer(); strBuff.append(primary_id); strBuff.append(secondary_id); strBuff.append(date); strBuff.append(desc); String str = strBuff.toString(); int hashCode = str.hashCode(); return ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access