implement equals and hashcode in hibernate code example

Example: impement hashcode equals in hiberante

@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