jpa specification equals hascoe

Solutions on MaxInterview for jpa specification equals hascoe by the best coders in the world

showing results for - "jpa specification equals hascoe"
Alexa
13 Jan 2020
1// 2 transient entities need to be NOT equal
2MyEntity e1 = new MyEntity("1");
3MyEntity e2 = new MyEntity("2");
4Assert.assertFalse(e1.equals(e2));
5 
6// 2 managed entities that represent different records need to be NOT equal
7e1 = em.find(MyEntity.class, id1);
8e2 = em.find(MyEntity.class, id2);
9Assert.assertFalse(e1.equals(e2));
10 
11// 2 managed entities that represent the same record need to be equal
12e1 = em.find(MyEntity.class, id1);
13e2 = em.find(MyEntity.class, id1);
14Assert.assertTrue(e1.equals(e2));
15 
16// a detached and a managed entity object that represent the same record need to be equal
17em.detach(e1);
18e2 = em.find(MyEntity.class, id1);
19Assert.assertTrue(e1.equals(e2));
20 
21// a re-attached and a managed entity object that represent the same record need to be equal
22e1 = em.merge(e1);
23Assert.assertTrue(e1.equals(e2));
24
Florent
06 Jan 2017
1@Entity
2public class MyEntity {
3 
4    @Id
5    @GeneratedValue(strategy = GenerationType.AUTO)
6    private Long id;
7 
8    private LocalDate date;
9 
10    private String message;
11     
12    @NaturalId
13    private String businessKey;
14 
15    public MyEntity(String businessKey) {
16        this.businessKey = businessKey;
17    }
18     
19    private MyEntity() {}
20     
21    @Override
22    public int hashCode() {
23        return Objects.hashCode(businessKey);
24    }
25 
26    @Override
27    public boolean equals(Object obj) {
28        if (this == obj)
29            return true;
30        if (obj == null)
31            return false;
32        if (getClass() != obj.getClass())
33            return false;
34        MyEntity other = (MyEntity) obj;
35        return Objects.equals(businessKey, other.getBusinessKey());
36    }
37     
38    ...
39}
40