Java equals and database entities code example
Example 1: jpa specification equals hascoe
MyEntity e1 = new MyEntity("1");
MyEntity e2 = new MyEntity("2");
Assert.assertFalse(e1.equals(e2));
e1 = em.find(MyEntity.class, id1);
e2 = em.find(MyEntity.class, id2);
Assert.assertFalse(e1.equals(e2));
e1 = em.find(MyEntity.class, id1);
e2 = em.find(MyEntity.class, id1);
Assert.assertTrue(e1.equals(e2));
em.detach(e1);
e2 = em.find(MyEntity.class, id1);
Assert.assertTrue(e1.equals(e2));
e1 = em.merge(e1);
Assert.assertTrue(e1.equals(e2));
Example 2: jpa specification equals hascoe
@Entity
public class MyEntity {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private LocalDate date;
private String message;
@NaturalId
private String businessKey;
public MyEntity(String businessKey) {
this.businessKey = businessKey;
}
private MyEntity() {}
@Override
public int hashCode() {
return Objects.hashCode(businessKey);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
MyEntity other = (MyEntity) obj;
return Objects.equals(businessKey, other.getBusinessKey());
}
...
}