Java equals and database entities code example

Example 1: jpa specification equals hascoe

// 2 transient entities need to be NOT equal
MyEntity e1 = new MyEntity("1");
MyEntity e2 = new MyEntity("2");
Assert.assertFalse(e1.equals(e2));
 
// 2 managed entities that represent different records need to be NOT equal
e1 = em.find(MyEntity.class, id1);
e2 = em.find(MyEntity.class, id2);
Assert.assertFalse(e1.equals(e2));
 
// 2 managed entities that represent the same record need to be equal
e1 = em.find(MyEntity.class, id1);
e2 = em.find(MyEntity.class, id1);
Assert.assertTrue(e1.equals(e2));
 
// a detached and a managed entity object that represent the same record need to be equal
em.detach(e1);
e2 = em.find(MyEntity.class, id1);
Assert.assertTrue(e1.equals(e2));
 
// a re-attached and a managed entity object that represent the same record need to be equal
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());
    }
     
    ...
}

Tags:

Java Example