During development of my test project I found one problem. Here is my entity class example
@Entity
@Table(name = "COMPANY_BRANCH")
@SQLDelete(sql = "UPDATE COMPANY_BRANCH SET DELETED = true WHERE id=?")
@Where(clause = "DELETED=false")
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class CompanyBranch extends AbstractAggregateRoot<CompanyBranch> {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof CompanyBranch that)) return false;
return Objects.equals(id, that.id);
}
@Override
public int hashCode() {
return Objects.hash(id);
}
}
When I am trying to compare two companyBranches like this:
taskGiver.getCompanyBranch().equals(taskReceiver.getCompanyBranch());
I am getting false, BUT in cosole I can see that the ids are the same:
2024-05-13T22:46:59.212+03:00 INFO 16664 --- [ main] c.m.e.task.controller.TaskController : COMPANY BRANCH ID1: 1, COMPANY BRANCH ID2: 1
Here is the piece of code where I am comparing:
private boolean isHeadOfCorrectDepartment(Employee taskGiver, Employee taskReceiver) {
log.info("COMPANY BRANCH ID1: {}, COMPANY BRANCH ID2: {}", taskGiver.getCompanyBranch().getId(), taskReceiver.getCompanyBranch().getId());
boolean isCompanyBranchesEqual = taskGiver.getCompanyBranch().equals(taskReceiver.getCompanyBranch());
boolean isDepartmentEqual =
taskGiver.getPosition().getDepartment().equals(taskReceiver.getPosition().getDepartment());
log.info("COMPANY BRANCHES EQUAL: {} DEPARTMENTS EQUAL: {}", isCompanyBranchesEqual, isDepartmentEqual);
return isCompanyBranchesEqual && isDepartmentEqual;
}
So the same thing happens with my Department entity, BUT all is fine when I am comparing the ids by themselfes like this:
boolean isCompanyBranchesEqual = taskGiver.getCompanyBranch().getId()
.equals(taskReceiver.getCompanyBranch().getId());
boolean isDepartmentEqual = taskGiver.getPosition().getDepartment().getId()
.equals(taskReceiver.getPosition().getDepartment().getId());
Then everything is fine. So am I missing something in how equals
works in Spring Data Jpa? Or maybe something wrong with my equals
method?