Re: suggestion: CayenneDataObject equals()

From: Andrus Adamchik (
Date: Sat Sep 18 2004 - 20:42:54 EDT

  • Next message: Andrus Adamchik: "Re: rtrim()"


    "equals()" and "hashCode()" are not implemented for CayenneDataObject,
    as Cayenne DataContext works based on the idea of "uniquing". I.e.
    within a given DataContext there can be only one instance of an object
    with a given ObjectId, and if an object is registered with a different
    DataContext, it is a different object. So superclass (java.lang.Object)
    implementation of "equals" is quiet appropriate.

    Actually in most cases you can simply do "object1 == object2"
    comparison. On the other hand if you want to compare objects across
    DataContexts, comparing ObjectIds explicitly is the way to go (that's
    what you have in your example), but doing this at the DataObject level
    will not be correct.


    On Sep 18, 2004, at 3:03 PM, Bryan Lewis wrote:
    > I was doing some load-testing (trying out JMeter actually) and came
    > across a subtle bug. The app under test had a line:
    > if (employeeRole.equals(currentRole))
    > which had always worked fine before. But when I started two simulated
    > user sessions in two browsers, the line was returning false in the
    > second session, even though the objects appeared to be identical.
    > (They printed the same, down to the hex codes.) I think it's some
    > kind of classloader thing, running in JBoss 3.2.5 + Tomcat 5.
    > I noticed in the Cayenne source code that ObjectId.equals() is careful
    > not to be fooled by different class loaders, so I added an equals()
    > method to my DataObject superclass:
    > public boolean equals(Object o)
    > {
    > if (o == this) {
    > return true;
    > }
    > if (o == null || !(o instanceof CayenneDataObject)) {
    > return false;
    > }
    > CayenneDataObject other = (CayenneDataObject) o;
    > return getObjectId().equals(other.getObjectId());
    > }
    > That fixed the problem for me. It would probably be a good idea to
    > add such a method to CayenneDataObject to make sure this doesn't trip
    > up other developers. Along with a corresponding hashCode() method:
    > /**
    > * Always override hashCode() when equals() is overridden, to make
    > * sure that two equal objects have the same hashCodes.
    > * See "Effective Java", page 33.
    > */
    > public int hashCode()
    > {
    > return getObjectId().hashCode();
    > }
    > Thanks,
    > Bryan Lewis

    This archive was generated by hypermail 2.0.0 : Sat Sep 18 2004 - 20:42:58 EDT