java:S2097 False positive in JPA Buddy-style equals

  • What language is this for? → Java
  • Which rule? → java:S2097

Hi, we have a Hibernate entity class with equals and hashCode implemented as explained in https://jpa-buddy.com/blog/hopefully-the-final-article-about-equals-and-hashcode-for-jpa-entities-with-db-generated-ids/ and now we get a new reliability issue because of java:S2097 stating that there is no type test inside the equals method.

The code is as follows:

@Override
public final boolean equals(Object o) {
    if (this == o) return true;
    if (o == null) return false;
    Class<?> oEffectiveClass = o instanceof HibernateProxy oHibernateProxy ? oHibernateProxy.getHibernateLazyInitializer().getPersistentClass() : o.getClass();
    Class<?> thisEffectiveClass = this instanceof HibernateProxy thisHibernateProxy ? thisHibernateProxy.getHibernateLazyInitializer().getPersistentClass() : this.getClass();
    if (thisEffectiveClass != oEffectiveClass) return false;
    MyEntity myEntity = (MyEntity) o;
    return getId() != null && Objects.equals(getId(), myEntity.getId());
}

the class containing this method is called MyEntity and there is a type test (if (thisEffectiveClass != oEffectiveClass))

We’re using SonarQube Server Developer Edition v2025.4.2

Hey there!

I think we’re tracking this FP at SONARJAVA-4660. Can you take a look and confirm? If so, I’ll link this thread to that ticket.

Hi Colin,

I don’t think this is the same issue as we’re not testing the type via Object.equals.

@kim.martin, yes, the rule S2097 does not understand the pattern instanceof, it’s a bug.
I created the Jira ticket SONARJAVA-5765 to fix this.
Thanks for your feedback.