复合id类的hashCode()和equals()方法

时间:2014-07-15 08:00:45

标签: java hibernate many-to-many equals hashcode

我一直试图找到实现复合id类的equals()和hashCode()方法的正确方法。

我尝试更新主要对象(Gara)时遇到的麻烦是:

  1. 的StackOverflow
  2. DuplicateKeyException:具有相同标识符值的其他对象已与会话
  3. 关联
  4. org.hibernate.ObjectNotFoundException:不存在具有给定标识符的行
  5. 我的Composite-id类

    @Embeddable 
    public class GaraAgenziaId implements Serializable {
    
        private static final long serialVersionUID = 4934033367128755763L;
    
        static Logger logger = LoggerFactory.getLogger(GaraAgenziaId.class);
    
        private Gara gara;
    
        private Agenzia agenzia;
    
        @ManyToOne
        public Gara getGara() {
            return gara;
        }
    
        public void setGara(Gara gara) {
            this.gara = gara;
        }
    
        @ManyToOne
        public Agenzia getAgenzia() {
            return agenzia;
        }
    
        public void setAgenzia(Agenzia agenzia) {
            this.agenzia = agenzia;
        }
    
    
        @Override
        public String toString() {
            return "GaraAgenziaId [Gara=" + gara + ", agenzia=" + agenzia
                    + "]";
        }
    
    
    }
    

1 个答案:

答案 0 :(得分:4)

这些看起来效果很好:

 public boolean equals(Object o) {
        if (this== o) return true;
        if (o ==null|| getClass() != o.getClass()) return false;

        GaraAgenziaId that = (GaraAgenziaId) o;

        if (gara !=null?!gara.equals(that.gara) : that.gara !=null) return false;
        if (agenzia !=null?!agenzia.equals(that.agenzia) : that.agenzia !=null)
            return false;

        return true;
    }

    public int hashCode() {
        int result;
        result = (agenzia !=null? agenzia.hashCode() : 0);
        result =31* result + (gara !=null? gara.hashCode() : 0);
        return result;
    }