Chapter 9. Design Strategies

The previous eight chapters have presented the core EJB technology. What’s left is a grab bag of miscellaneous issues: how do you solve particular design problems, how do you work with particular kinds of databases, and topics of that nature.

Hash Codes in Compound Primary Keys

Chapter 6 discusses the necessity of overriding the Object.hashCode() and Object.equals() methods in the primary key class. As an example, we used the primary key for the Ship bean, ShipPK . This is a simple primary key with a single integer field, id . Therefore, our hashCode() and equals() methods were very simple; hashCode() just returned the id field as the hash value. With complex primary keys that have several fields, overriding the Object.equals() method remains trivial. However, the Object.hashCode() method 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 ...

Get Enterprise JavaBeans, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.