Files
hibernate-demo/src/main/java/com/ankurm/hibernatedemo/persistenceannotations/IdBasedEqualsEntity.java
T

48 lines
1.2 KiB
Java
Executable File

package com.ankurm.hibernatedemo.persistenceannotations;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
import java.util.Objects;
/**
* The anti-pattern the article warns about in Q5: {@code equals()}/{@code hashCode()} based on
* the SURROGATE {@code @GeneratedValue} id. Before the first flush, {@code id} is null, so the
* object's hash code is fixed at "hash of null" -- then flush() mutates {@code id}, changing the
* hash code out from under any HashSet/HashMap the object is already sitting in.
*
* <p>Docs: docs/05-jpa-persistence-annotations.md, Topic 2.
*/
@Entity
public class IdBasedEqualsEntity {
@Id
@GeneratedValue
private Long id;
private String label;
public IdBasedEqualsEntity() {
}
public IdBasedEqualsEntity(String label) {
this.label = label;
}
public Long getId() {
return id;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof IdBasedEqualsEntity that)) return false;
return Objects.equals(id, that.id);
}
@Override
public int hashCode() {
return Objects.hash(id);
}
}