简体   繁体   English

Spring Data JPA save()方法未遵循哈希码/等于合约

[英]Spring Data JPA save() method not following the hashcode/equals contract

I am facing problems implementing hashcode/equals in a simple Employee Entity below. 我在下面的简单员工实体中实现哈希码/等于问题。 My custom field upon which i want to implement equality is the "_id" field. 我要在其上实现相等性的自定义字段是“ _id”字段。

When i save two employee objects with the same value ie "111", I expect to save only one value in the database. 当我用相同的值(即“ 111”)保存两个员工对象时, 我希望在数据库中只保存一个值。 However, i end up saving 2 employee records. 但是,我最终保存了2条员工记录。

The entity code is as below 实体代码如下

    @Entity
    @Table(name = "employee")
    public class Employee {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "employee_id")
    private Long employeeId;

    @Column(name = "employeehexa_id") 
    private String _id;

    @Override
    public int hashCode() {
        HashCodeBuilder hcb = new HashCodeBuilder();
        hcb.append(_id);
        return hcb.toHashCode();
    }   


    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (!(obj instanceof Employee)) {
            return false;
        }
        Employee that = (Employee) obj;
        EqualsBuilder eb = new EqualsBuilder();
        eb.append(_id, that._id);
        return eb.isEquals();
    }

    // Required Constructors, getters, setters not shown for brevity
   }

And the below is my call to save two object with same _id 下面是我的调用以保存两个具有相同_id的对象

@Autowired
private EmployeeRepo employeeRepo;

@RequestMapping("/test")
String Test() throws Exception {

    Employee e1 = new Employee("111");
    Employee e2 = new Employee("111");
     System.out.println(e1.equals(e2)); // prints true, implying hashcode and equals working fine
    employeeRepo.save(e1);
    employeeRepo.save(e2);//Both e1 and e2 are saved inspite of being equal

    return "Completed !";
}

The equality check seems to work fine. 平等检查似乎很好。 Is there something about save() of spring JpaRepository that causes this or is my understanding of how equality/hashcode contract is enforced incorrect ? spring JpaRepository的save()是否有引起这种情况的原因,或者我对平等/哈希码合同的强制执行方式的理解是否正确?

I thought i understood equality/hashcode but looks like that is not the case. 我以为我了解平等/哈希码,但事实并非如此。 Any help appreciated. 任何帮助表示赞赏。 Thx. 谢谢。

According to this answer, https://stackoverflow.com/a/11881628/5695673 , you probably have 2 records because your fields employeeId are differents for your entities, so for spring-data the two entities are differents. 根据这个答案https://stackoverflow.com/a/11881628/5695673 ,您可能有2条记录,因为您的字段employeeId对于您的实体是不同的,因此对于spring-data,这两个实体是不同的。
To test if your equals()/hashCode() works as expected, you can try to put your entities in a collection which check object equality (ie a Set ) and try to save all the set in one time. 要测试equals()/hashCode()按预期工作,可以尝试将实体放入检查对象是否相等的集合(即Set )中,并尝试一次保存所有集合。

Example: 例:

Set<Employee> employees = new HashSet<Employee>();
employees.add( new Employee("111"));
employees.add( new Employee("111"));

System.out.println(employees.size()); //1
employeeRepo.save(employees); // 1 record

More information here: https://developer.jboss.org/wiki/EqualsandHashCode?_sscc=t 此处提供更多信息: https : //developer.jboss.org/wiki/EqualsandHashCode?_sscc=t

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM