diff --git a/documentation/src/main/asciidoc/introduction/Entities.adoc b/documentation/src/main/asciidoc/introduction/Entities.adoc index e57f77224c..4329db9231 100644 --- a/documentation/src/main/asciidoc/introduction/Entities.adoc +++ b/documentation/src/main/asciidoc/introduction/Entities.adoc @@ -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 <>. +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. \ No newline at end of file diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/NaiveEqualsHashCodeEntityTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/NaiveEqualsHashCodeEntityTest.java index f31d2f25eb..013f87b953 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/NaiveEqualsHashCodeEntityTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/NaiveEqualsHashCodeEntityTest.java @@ -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 diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/NaturalIdEqualsHashCodeEntityTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/NaturalIdEqualsHashCodeEntityTest.java index 7b5f794cc6..c5ce23e9a9 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/NaturalIdEqualsHashCodeEntityTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/NaturalIdEqualsHashCodeEntityTest.java @@ -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