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;
}
}