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.
When i save two employee objects with the same value i.e. "111", I expect to save only one value in the database. However, i end up saving 2 employee records.
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
@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 ?
I thought i understood equality/hashcode but looks like that is not the case. Any help appreciated. Thx.