As recommended in HIA and the reference docs, my objects implement equals and hashCode using 'business key equality', or 'the natural key I would be using if I wasn't using surrogate keys'. This means that they exclude the identifier property (because that breaks sets on save in the well understood way), but they do sometimes include the identifier properties of their associations.
Consider the parent-child example:
Code:
class Parent
{
Long id;
Set<Child> children;
}
class Child
{
Long id;
Parent parent;
String name;
boolean equals(Object rhs)
{
//equate on name and parent.getId()
}
}
The problem arises when a save cascades from parent to child. Hibernate updates both entities identifier properties with the newly generated values, which means the child's hashcode changes (because parent.getId() was null before but it isn't now!) while it is in the parent's set, breaking the set. I basically have to do a refresh() on the root entity to get around this.
Am I missing something here? Is the business key not supposed to include associations? How do you implement equality on a class representing an association table then?