package com.ankurm.hibernatedemo.naturalid; import jakarta.persistence.Column; import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; import jakarta.persistence.Id; import java.util.Objects; import org.hibernate.Hibernate; import org.hibernate.annotations.NaturalId; /** * equals()/hashCode() based on the IMMUTABLE natural id (sku), assigned in the constructor -- * exactly the pattern posts 4864/4865 recommend. Since sku is set before the object ever enters * a Set/Map (unlike a surrogate id, which is null until flush), the hash code should be STABLE * across persist(). This entity exists to test whether that advice actually holds up. * *
Docs: docs/06-natural-ids.md, Topic 3. */ @Entity public class NaturalIdEqualsEntity { @Id @GeneratedValue private Long id; @NaturalId @Column(nullable = false, unique = true, updatable = false) private final String sku; private String name; protected NaturalIdEqualsEntity() { this.sku = null; // JPA no-arg constructor requirement } public NaturalIdEqualsEntity(String sku, String name) { this.sku = sku; this.name = name; } public Long getId() { return id; } public String getSku() { return sku; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null) return false; if (Hibernate.getClass(this) != Hibernate.getClass(o)) return false; NaturalIdEqualsEntity that = (NaturalIdEqualsEntity) o; return Objects.equals(sku, that.sku); } @Override public int hashCode() { return Objects.hash(sku); } }