• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Entity bean with composite key

 
Meg Adal
Ranch Hand
Posts: 70
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 11
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 79
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic