How to write hasCode() & equals(0) methods in Compound Key Class

View: New views
1 Messages — Rating Filter:   Alert me  

How to write hasCode() & equals(0) methods in Compound Key Class

by Henry Tran :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

Some parts of this message have been removed. Learn more about Nabble's security policy.
Hi All,

I am wondering how to write the hashCode() and equals() methods that is mandatory when creating composite

@IdClass. Below is the combination of primary @Id keys that I would like to make up in a compound key class:


public final class PatientKey implements java.io.Serializable
{
private String firstnameId;
private String SurnameId;
private String DateOfBirthID;
private String Sex;

public int hashCode()
{
.....
}

public boolean equals(Object otherOb)
{
......
}

......
}


The Order application in Java EE 5 Tutorial (page 841) is made up of only 2 primary keys.

Below is an example of the primary compound class key I am trying to replicate. It is the LineItemKey class that is part of the Order application from the same tutorial:


public class LineItemKey implements Serializable {
private Integer orderId;
private int itemId;

public LineItemKey() {
}

public LineItemKey(
Integer orderId,
int itemId) {
this.setOrderId(orderId);
this.setItemId(itemId);
}

public int hashCode() {
return (((this.getOrderId() == null) ? 0 : this.getOrderId()
.hashCode())
^ ((int) this.getItemId()));
}

public boolean equals(Object otherOb) {
if (this == otherOb) {
return true;
}

if (!(otherOb instanceof LineItemKey)) {
return false;
}

LineItemKey other = (LineItemKey) otherOb;

return (((this.getOrderId() == null) ? (other.getOrderId() == null)
: this.getOrderId()
.equals(other.getOrderId()))
&& (this.getItemId() == other.getItemId()));
}
.....
}

These methods are making comparison between 2 objects based on their properties. I would like to achieve the same thing in an identical compound class (@IdClass) based on at least 4 or more properties. ie firstname, surname, dob and sex.

Thanks,

Henry


Get the name you always wanted with the new y7mail email address.
LightInTheBox - Buy quality products at wholesale price