Home > Blockchain >  Should I use getters or fields in JPA entity equals methods?
Should I use getters or fields in JPA entity equals methods?

Time:12-09

When writing an equals method for my JPA entity, should I access the fields directly, or should I go through the getters?

In other words, do I do this?

@Override
public boolean equals(Object o) {
    if (this == o) return true;
    if (!(o instanceof Book)) return false;
    Book book = (Book) o;
    return Objects.equals(getIsbn(), book.getIsbn());
}

Or this?

@Override
public boolean equals(Object o) {
    if (this == o) return true;
    if (!(o instanceof Book)) return false;
    Book book = (Book) o;
    return Objects.equals(isbn, book.isbn);
}

In this context, does it matter if I place the JPA annotations on the fields or on the getters? Also, does it matter if I use FetchType.LAZY (I imagine it would)? I read somewhere that lazy fields aren't materialized if you access by field and the annotation is placed on the getter (they'll remain null or empty), but does it happen when the annotation is placed on the field?

Does the behaviour differ between Hibernate and other vendors?

I googled, and even opened a book, but I'm kind of a JPA noob and I couldn't find a definitive answer to this question (although I did notice that experts tend to use getters in their blogs, such as enter image description here

  • Related