0

I need some thoughts on this implementation of hashCode and equals for Hibernate entities.

The main goal is to identify two same objects representing row in db and distinguish them from unsaved objects and remove or add items to relations represented with Set<> collection.

@Data
@MappedSuperclass
public class BaseEntity {

    @Id
    @Column(name = "id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    private static AtomicLong idGenerator = new AtomicLong(Long.MIN_VALUE);

    @Transient
    private long instanceId = idGenerator.incrementAndGet();

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || !(o instanceof BaseEntity)) return false;
        BaseEntity c = (BaseEntity) o;
        return (this.id != 0 && c.id != 0) && this.id == c.id;
    }

    @Override
    public int hashCode() {
        if (id != 0) { return (int) (id % Integer.MAX_VALUE); }
        int i = (int) (instanceId % Integer.MAX_VALUE);
        return i < 0 ? i : -i;
    }
}
Mihael Mamula
  • 330
  • 3
  • 11
  • 2
    Please read this article: https://vladmihalcea.com/how-to-implement-equals-and-hashcode-using-the-jpa-entity-identifier/ and if you then have questions please ask again. – Simon Martinelli Jan 17 '18 at 20:29
  • 1
    Possible duplicate of [The JPA hashCode() / equals() dilemma](https://stackoverflow.com/questions/5031614/the-jpa-hashcode-equals-dilemma) – crizzis Jan 17 '18 at 20:30
  • @SimonMartinelli Thank You for a suggestion. NaturalId seams as best solution there but will require an update of existing tables though. – Mihael Mamula Jan 17 '18 at 20:50

0 Answers0