How to Use Hibernate Natural Ids and Business Keys
Use Hibernate natural ids and business keys: map @NaturalId, look up by business key with caching, implement equals and hashCode safely and add constraints.

Most entities have two identities. The technical one is the primary key, usually a generated number, which the database uses for joins and foreign keys. The business one is the attribute people use to find the thing: the ISBN of a book, the email of an account, the SKU of a product. Hibernate calls the second a natural id, and it has support for it that most projects never use. This post shows the mapping, the lookup API and its cache, the part that solves the old equals and hashCode problem for entities, and the cases where a natural id is a bad idea. It uses Hibernate 7 on JDK 25.
Mapping
@Entity
public class Book {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NaturalId
@Column(nullable = false, length = 17)
private String isbn;
@Column(nullable = false)
private String title;
protected Book() { }
public Book(String isbn, String title) {
this.isbn = isbn;
this.title = title;
}
public String getIsbn() { return isbn; }
// other getters
}@NaturalId marks isbn as the business key. Hibernate generates a unique constraint on the column when it creates the schema, so duplicates are rejected by the database. By default a natural id is immutable: Hibernate throws an exception if you change it on a loaded entity, which fits an ISBN. A composite natural id puts the annotation on several fields, and the constraint covers the combination, such as (country, taxNumber).
Mark the column nullable = false, because a natural id with nulls is not an identity.
Look up by natural id
Book book = session.bySimpleNaturalId(Book.class).load("978-0-13-468599-1");
Optional<Book> maybe = session.bySimpleNaturalId(Book.class).loadOptional("978-0-13-468599-1");
Book composite = session.byNaturalId(Tax.class)
.using("country", "DE").using("number", "12345").load();bySimpleNaturalId is for an entity with one natural id attribute and byNaturalId for several. With Spring Data you can still write findByIsbn(String isbn) and get a query, which is fine. The Hibernate API earns its place through caching. With the second-level cache enabled and @NaturalIdCache on the entity, Hibernate stores the mapping from natural id to primary key, so a lookup by ISBN for an entity that is already cached needs no query at all. Without the cache, it runs a select by the natural id column, the same as the repository method.
@Entity
@NaturalIdCache
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class Book { /* ... */ }Use this for reference data that is read far more often than it changes, such as countries, currencies and catalogue entries. Do not use it for data that changes constantly, since each change invalidates entries. The cache needs a provider configured in hibernate.cache.* properties, which is a topic of its own.
equals and hashCode
Entities pose a notorious problem. Two Book objects loaded in different sessions represent the same row and should be equal. A generated id is null until the row is saved, so an equals based on id treats two new entities as equal, and a hashCode based on id changes when the id is assigned, which corrupts any HashSet that held the object. Basing equality on all fields breaks as soon as a field changes. A natural id is the right basis, since it is set at construction and does not change:
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Book other)) return false;
return Objects.equals(isbn, other.isbn);
}
@Override
public int hashCode() {
return Objects.hashCode(isbn);
}This is stable across transient, persistent and detached states. Using instanceof rather than getClass() works with Hibernate's proxies, which are subclasses. The Objects.equals(isbn, other.isbn) field access, not other.getIsbn(), matters on a proxy: reading the field of an uninitialised proxy returns null, so use the getter on other. The general problem is in JPA equals and hashCode, the entity design in mapping the first entity, and why you may want to avoid Lombok's generated versions on entities in Lombok versus records.
Mutable natural ids
Some business keys change: people change email addresses. @NaturalId(mutable = true) allows it. Hibernate then tracks the old value, so that its natural id cache stays correct, and the unique constraint still holds. The price is that the key is no longer a safe basis for equals and hashCode: a value that changes while the object is in a HashSet breaks the set. For mutable keys, choose the generated id for equality and handle the new-entity problem separately, or avoid putting such entities in hashed collections.
Ask honestly whether the key is stable. An email address looks like a natural id and changes more often than you expect. A national identifier looks stable and is sometimes corrected or reissued. If the business can change it, treat it as an ordinary unique column.
Setting it right at construction
Because the natural id is the basis of equality, set it in the constructor and keep it out of the setters. The protected no-argument constructor exists for Hibernate; application code should only be able to create a Book with an ISBN. Validate the format there too, so that an object with a malformed key cannot exist. An ISBN check digit, a lower-cased email, a trimmed SKU: normalise before assigning, because the unique constraint compares exactly what you store, and "[email protected]" and "[email protected]" are two rows unless you decide otherwise. For case-insensitive keys, store the normalised form in the natural id column and keep the display form in another.
Finally, tests. A test that saves two books with the same ISBN and expects a constraint violation proves the schema rule exists, and a test that loads a book in two sessions and asserts equality proves the equals works across them. Both take a few lines with a @DataJpaTest, and they catch the day someone replaces the implementation with an IDE-generated one that includes the id.
Keep the surrogate key
A natural id does not replace the primary key. Foreign keys should reference the numeric id: it is small, it is never edited, it indexes well and it does not leak business data into every child table. If you use the ISBN as a foreign key and a publisher corrects it, you update every referencing row. Keep the generated id for the relational structure and use the natural id for lookups and equality.
Schema
create table book (
id bigint generated by default as identity primary key,
isbn varchar(17) not null,
title varchar(255) not null,
constraint uk_book_isbn unique (isbn)
);The unique constraint is the important line. Create it in your migration, not only through Hibernate's schema generation, since production schemas are managed by Flyway or Liquibase. Name it explicitly, so the error message on a duplicate tells you which rule was broken. In domain-driven terms, the natural id often corresponds to the identity of an aggregate root, as described in aggregates and value objects.
When this does not apply
Entities without a stable business key, such as an event log row or an audit entry, have only a surrogate identity, and equals can use the id once assigned or fall back to identity equality. The mapping is documented in the NaturalId Javadoc and the user guide chapter.


