Object equality in context of hibernate / webapp

后端 未结 5 720
孤城傲影
孤城傲影 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);
        }
    }
    

提交回复
热议问题