HHH-17555 don't use getClass() inside entity equals()

This commit is contained in:
Gavin King 2023-12-12 14:34:40 +01:00
parent d3027907c2
commit 5ca64dba8b
3 changed files with 14 additions and 7 deletions

View File

@ -1579,18 +1579,25 @@ class Book {
@Basic(optional=false)
String isbn;
String getIsbn() {
return isbn;
}
...
@Override
public boolean equals(Object other) {
return other instanceof Book
&& ((Book) other).isbn.equals(isbn);
return other instanceof Book // check type with instanceof, not getClass()
&& ((Book) other).getIsbn().equals(isbn); // compare natural ids
}
@Override
public int hashCode() {
return isbn.hashCode();
return isbn.hashCode(); // hashcode based on the natural id
}
}
----
That said, an implementation of `equals()` and `hashCode()` based on the generated identifier of the entity can work _if you're careful_.
CAUTION: Your implementation of `equals()` must be written to accommodate the possibility that the object passed to the `equals()` might be a <<proxies-and-lazy-fetching,proxy>>.
Therefore, you should use `instanceof`, not `getClass()` to check the type of the argument, and should access fields of the passed entity via its accessor methods.

View File

@ -185,11 +185,11 @@ public class NaiveEqualsHashCodeEntityTest extends BaseEntityManagerFunctionalTe
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
if (!(o instanceof Book)) {
return false;
}
Book book = (Book) o;
return Objects.equals(id, book.id);
return Objects.equals(id, book.getId());
}
@Override

View File

@ -164,11 +164,11 @@ public class NaturalIdEqualsHashCodeEntityTest extends BaseEntityManagerFunction
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
if (!(o instanceof Book)) {
return false;
}
Book book = (Book) o;
return Objects.equals(isbn, book.isbn);
return Objects.equals(isbn, book.getIsbn());
}
@Override