Reputation: 47068
There are a lot of articles that cover how to implement hashcode
and equals
for JPA entities.
Instead of worrying about this for every single JPA entity created, would it be simpler to set a final
and updatable = false
id
property to a UUID
and base the hashcode
and equals
implementations on that id? Any drawbacks to doing it this way?
Upvotes: 2
Views: 697
Reputation: 153960
Why add a new extra column or use UUID which does not play well with MySQL clustered indexes when you can implement equals
and hashCode
based on the AUTO_INCREMENTED
or SEQUENCE-based Primary Key?
So, this is how your implementations would look like:
@Entity
public class Book implements Identifiable<Long> {
@Id
@GeneratedValue
private Long id;
private String title;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Book)) return false;
Book book = (Book) o;
return getId() != null && Objects.equals(getId(), book.getId());
}
@Override
public int hashCode() {
return getClass().hashCode();
}
//Getters and setters omitted for brevity
}
The constant getClass().hashCode()
value is for making sure it is consistent across all entity state transitions.
Upvotes: 2