The Hibernate mapping tool generated this equals() method for AbstractFoo.java:
public boolean equals(Object rhs)
{
if (rhs == null)
return false;
if (! (rhs instanceof Foo))
return false;
Foo that = (Foo) rhs;
if (this.getRowId() != null && that.getRowId() != null)
{
if (! this.getRowId().equals(that.getRowId()))
{
return false;
}
}
return true;
}
The primary key in this case is a String, which is null until Hibernate assigns a value, which may not occur until the session is flushed.
This method returns true between any two new unsaved instances of Foo. It also returns true if (this.getRowId() == null && that.getRowId() != null). The way equals() is written, I’ll never be able to add more than one unsaved instance of Foo to a Set. These observations also hold true for when the right hand side is a subclass of Foo.
Also, take a look at the hash code method:
public int hashCode()
{
if (this.hashValue == 0)
{
int result = 17;
int rowIdValue = this.getRowId() == null ? 0 : this.getRowId().hashCode();
result = result * 37 + rowIdValue;
this.hashValue = result;
}
return this.hashValue;
}
So for all new (unsaved) instances of Foo the hashcode is the same? Better hope you don’t want to put more than a few of these in a Set or a Map!