Object equality in context of hibernate / webapp

后端 未结 5 631
孤城傲影
孤城傲影 2020-12-08 22:46

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

相关标签:
5条回答
  • 2020-12-08 23:07

    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);
        }
    }
    
    0 讨论(0)
  • 2020-12-08 23:13

    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.

    0 讨论(0)
  • 2020-12-08 23:15

    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

    0 讨论(0)
  • 2020-12-08 23:19

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

    @Transient
    private Integer otherId;
    
    0 讨论(0)
  • 2020-12-08 23:23

    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.

    0 讨论(0)
提交回复
热议问题