File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes EJB Certification (SCBCD/OCPJBCD) and the fly likes Entity bean with composite key Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Certification » EJB Certification (SCBCD/OCPJBCD)
Bookmark "Entity bean with composite key" Watch "Entity bean with composite key" New topic
Author

Entity bean with composite key

Meg Adal
Ranch Hand

Joined: Mar 12, 2002
Posts: 70
Here is the requirement.
Table A has records with Col1 (customerID) and Col2 (userID) creating composite key.
I was able to create entity bean for just Col1(customerID) as primary key with new class for primary key but not sure how to deal with composite key.

In the custom class for composite key how do I make sure that hashCode()and equals() methods are implemented correctly?

Any suggestions

Thanks in advance.
Vicky Bajaj
Greenhorn

Joined: Jun 30, 2003
Posts: 11
The hashCode method must return the same value for two objects which are equal, and it should attempt to distribute the hashCode values relatively evenly. The first implementation, shown below, is efficient and correct, but it does not distribute the hashCode values at all. This hashCode implementation transforms any hash table into a list and forces linear searches. Clearly, this defeats the whole purpose of having an indexed data structure
public class MyPk
implements java.io.Serializable
{
public String str;
public int i;
public byte b;
public MyPk() {}

private int hash = -1;
public int hashCode() {
if (hash == -1) {
hash = str.hashCode() ^ i ^ b;
}
return hash;
}
}

An efficient equals implementation
public final class MyPk ...
public boolean equals(Object o) {
if (o == this) return true;
if (o instanceof MyPk) {
MyPk other = (MyPk) o;
return other.hashCode() == hashCode() &&
other.i == i && other.b == b &&
other.str.equals(str);
} else {
return false;
}
}
Siripa Siangklom
Ranch Hand

Joined: Jan 26, 2004
Posts: 79
1.Override the equals() method to properly evaluate the equality of two primary keys by comparing values for each part of the composite key.

2.Override the Object.hashCode() method to return a unique number representing the hash code for the primary key instance. Ensure that the hash code is indeed unique when you use your primary key attribute values to compute the hash code.
 
Don't get me started about those stupid light bulbs.
 
subject: Entity bean with composite key
 
Similar Threads
Entity bean
Creation of CMP Entity bean with a Composite Primary Key???
CMR entity beans and primary key.
hashcode() & equals() method in Entity Bean
Composite primary key