When defining equals(), hashCode(), toString(), and compareTo() for a model object, you can either include references to objects you own (are composed of) or those that own you, but not both (else you’ll have an infinite loop on your hands).
For example, a Portfolio is composed of one or more Accounts. Either Portfolio.equals() can include the Accounts in its calculation (e.g., through Jakarta Commons Lang’s EqualsBuilder, or Account.equals() can include the Portfolio that it’s a part of, but not both. One could use neither, but I think this leaves out important information.
There’s a conceptual modeling argument to be made for including references with composition (i.e., putting the reference in Portfolio.equals(), but the relationship is not usually modeled this way in the database, and I’d prefer to keep things simple and follow the data structure. In other words:
public class Account ... {
...
public boolean equals(Object object) {
if (this == object) {
return true;
}
if (object instanceof Account == false) {
return false;
}
Account rhs = (Account) object;
return new EqualsBuilder().append(this.id, rhs.id).append(this.name,
rhs.name).append(this.portfolio, rhs.portfolio).isEquals();
}
}
December 17, 2006 at 1:55 am |
[...] While browsing for Spring/Hibernate/JPA stuff today, I found this little article on a blog. [...]