我一直在寻找正确的方法来实现Composite-id类的equals()和hashCode()方法。

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

  • StackOverflow
  • DuplicateKeyException:具有相同标识符值的另一个对象已与 session
  • 关联
  • org.hibernate.ObjectNotFoundException:不存在具有给定标识符的行

  • 我的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
                    + "]";
        }
    
    
    }
    

    最佳答案

    这些似乎很好地工作:

     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;
        }
    

    09-25 21:01