views:

229

answers:

5

How do you handle object equality for java objects managed by hibernate? In the 'hibernate in action' book they say that one should favor business keys over surrogate keys.
Most of the time, i do not have a business key. Think of addresses mapped to a person. The addresses are keeped in a Set and displayed in a Wicket RefreshingView (with a ReuseIfEquals strategy).

I could either use the surrogate id or use all fields in the equals() and hashCode() functions.
The problem is that those fields change during the lifetime ob the object. Either because the user entered some data or the id changes due to JPA merge() being called inside the OSIV (Open Session in View) filter.

My understanding of the equals() and hashCode() contract is that those should not change during the lifetime of an object.

What i have tried so far:

  • equals() based on hashCode() which uses the database id (or super.hashCode() if id is null). Problem: new addresses start with an null id but get an id when attached to a person and this person gets merged() (re-attached) in the osiv-filter.
  • lazy compute the hashcode when hashCode() is first called and make that hashcode @Transitional. Does not work, as merge() returns a new object and the hashcode does not get copied over.

What i would need is an ID that gets assigned during object creation I think. What would be my options here? I don't want to introduce some additional persistent property. Is there a way to explicitly tell JPA to assign an ID to an object?

Regards

A: 

Maybe a transient property would do it? That way you don't have to worry about the persistence. Like this:

@Transient
private Integer otherId;
Lars Andren
A: 

I use to do it that way: equal and hashcode use the key when it has been set, otherwise equals uses the base implementation (aka ==). It should work too if hashcode() returns super.hashcode() instead of 0.

@Override
public int hashCode() {
    if (code == null) {
        return 0;
    } else {
        return code.hashCode();
    }
}

@Override
public boolean equals(Object obj) {
    if (obj instanceof PersistentObject && Hibernate.getClass(obj).equals(Hibernate.getClass(this))) {
        PersistentObject po = (PersistentObject) obj;

        if (code == null) {
            return po.code == null && this == po;
        } else {
            return code.equals(po.getCode());
        }
    } else {
        return super.equals(obj);
    }
}
Guillaume
If i understand you correctly, this is what i did in my 1. bullet. But, since the Id gets set during the JPA merge() in the OSIV filter, i get a different hashCode, leading to equals() returning false for 2 equal object (equal, but not identical). this in turn makes the RefreshingView discard it item in the list, loosing the data entered by the user ..
bert
Good point, I'm not using these objects in a context where hashcode() needs to return a stable result. I guess returning a fixed value (eg. 0) would work but it defeats the purpose of hashing.
Guillaume
+3  A: 

Using the id of an entity is not a good idea because transient entities don't have an id yet (and you still want a transient entity to be potentially equal to a persistent one).

Using all properties (apart from the database identifier) is also not a good idea because all properties are just not part of the identity.

So, the preferred (and correct) way to implement equality is to use a business key, as explained in Java Persistence with Hibernate:

Implementing equality with a business key

To get to the solution that we recommend, you need to understand the notion of a business key. A business key is a property, or some combination of properties, that is unique for each instance with the same database identity. Essentially, it’s the natural key that you would use if you weren’t using a surrogate primary key instead. Unlike a natural primary key, it isn’t an absolute requirement that the business key never changes—as long as it changes rarely, that’s enough.

We argue that essentially every entity class should have some business key, even if it includes all properties of the class (this would be appropriate for some immutable classes). The business key is what the user thinks of as uniquely identifying a particular record, whereas the surrogate key is what the application and database use.

Business key equality means that the equals() method compares only the properties that form the business key. This is a perfect solution that avoids all the problems described earlier. The only downside is that it requires extra thought to identify the correct business key in the first place. This effort is required anyway; it’s important to identify any unique keys if your database must ensure data integrity via constraint checking.

For the User class, username is a great candidate business key. It’s never null, it’s unique with a database constraint, and it changes rarely, if ever:

    public class User {
        ...
        public boolean equals(Object other) {
            if (this==other) return true;
            if ( !(other instanceof User) ) return false;
            final User that = (User) other;
            return this.username.equals( that.getUsername() );
        }
        public int hashCode() {
            return username.hashCode();
        }
}

Maybe I missed something but for an Address, the business key would typically be made of the street number, the street, the city, the postal code, the country. I don't see any problem with that.

Just in case, Equals And HashCode is another interesting reading.

Pascal Thivent
thanks for your input. the problems i saw with it (guess i did not made myself clear enough) is:a) the hashcode changes as the user enters more datab) when the user presses the 'add address' button (just as an example) all fields are null (in your User example, the username is not yet given).I will have to read about the hashCode(), perhaps my memory is wrong (and a changing hashCode is not as evil as i remember) thanks
bert
You may want to replace "return this.username.hashCode()" to "return this.getUserName().hashCode()" and "return this.username.equals(that.getUserName())" to "return this.getUserName().equals(that.getUserName())". It's a better practice.
Robert Durgin
A: 

The question is how often are you likely to have multiple unsaved objects that might be duplicates that need to go into a set or map? For me, the answer is virtually never so I use surrogate keys and super.equals/hashcode for unsaved objects.

Business keys make sense in some cases, but they can cause problems. For example, what if two people live at the same address - if you want that to be one record in the database, then you have to manage it as a many-to-many and lose the ability to cascade delete it so when the last person living there is deleted, you have to do extra work to get rid of the address. But if you store the same addresss for each person then your business key has to include the person entity, which may mean a database hit inside your equals/hashcode methods.

Brian Deterling
with the usage of 'rarely' changing business keys i do see problems. Mayor problem is the rarely. If if that case is seldom, the sw still has to function properly. i 'm heading for surrogate keys right now. tanks.
bert
A: 

Thanks for all your input. I decided to use surrogate keys and provide those right at object creation time. This way i stay clear of all that 'rarely' changing stuff and have something solid to base identity on. First tests look rather good.

thank you all for your time. Unfortunately, i can only accept one answer as solution i will take Pascals, as he provided me with good reading ;)

enjoy

bert