What's wrong with KeyedMapper's implementation?
Well, that was exactly why I was asking the question, "Is this
implementation for equals and hashCode a good idea?" I had gotten
this at some point, been using it, and am only questioning it now
because if it truly is a good idea, I think it should be part of the
framework...
The hashCode implementation for KeyedMapper looks essentially the
same:
this.id.is.hashCode
vs.
primaryKeyField.is.hashCode
However, the equals implementation for KeyedMapper is a little
different:
override def equals (other : Any) = other match {
case t : Team if t.id.is == this.id.is => true
case _ => false
}
vs.
override def equals (other : Any) : Boolean = {
other match {
case null => false
case km: KeyedMapper[Nothing,Nothing] if
this.getClass.isAssignableFrom(km.getClass) ||
km.getClass.isAssignableFrom(this.getClass) =>
this.primaryKeyField == km.primaryKeyField
case k => super.equals(k)
}
}
There are some subtle differences. I have never used inheritance with
Mapper to make a complex class hierarchy, so I'm not 100% sure of the
ramifications (or if it is even possible).
Personally, I would imagine that two mapper objects are equal using a
primary key comparison only as long as they are read-only singletons.
If I had instance #1 loaded into val A and again into var B, then
modified some elements of B, I would no longer expect A to equal B --
but with the above implementation, they remain equal as long as the
primary key field is not altered.
In JPA/Hibernate land, I actually have a different approach for equals
and hashCode: each field is compared with the exception of the @Id
and @Version columns because they can change upon persistence, and so
are not part of the equality. I leverage Apache Commons-Lang
builders:
@Override
public boolean equals (final Object obj) {
return EqualsBuilder.reflectionEquals(this, obj,
EXCLUDE_FROM_EQUALS_AND_HASH_CODE);
}
@Override
public int hashCode () {
return HashCodeBuilder.reflectionHashCode(this,
EXCLUDE_FROM_EQUALS_AND_HASH_CODE);
}
/**
* Exclude fields from equals, hashCode, and compareTo that may
change upon
* persistence.
*
* @see <a href="http://www.hibernate.org/109.html">Best
strategies for
* implementation of equals() and hashcode() in your persistent
classes.</a>
*/
private static final String [] EXCLUDE_FROM_EQUALS_AND_HASH_CODE =
{"id", "version"};
So, if Hibernate suggests that you should NOT just compare the primary
key field, why should Lift-Mapper be doing that?
--
You received this message because you are subscribed to the Google Groups
"Lift" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/liftweb?hl=en.