Scrivio Interview library
ConceptFoundations6 min read · updated 12 November 2026

What is a Hibernate @NaturalId, and how does it differ from the primary key? Show how to load an entity by natural id.

@NaturalId marks a business key, such as an ISBN or an email, that is unique and usually never changes, while the primary key stays a surrogate id with no business meaning. We load by it with session.bySimpleNaturalId(Book.class).load(isbn), or with byNaturalId(...).using(...) for keys made of several attributes, and Hibernate caches the natural id to id resolution, so an entity already in the persistence context is found without a query. @NaturalId(mutable = true) allows the key to change at the cost of extra checks, and we still add a unique constraint in the database, because Hibernate creates it only when it generates the schema.

Why this question is asked

Most entities have two identities: the id the database uses for joins, and the key that people actually use to find things, such as an ISBN, an email or a country code. Hibernate has first-class support for the second kind, which many developers never use, writing a JPQL query instead every time. Interviewers ask about it to see whether we know the difference between surrogate and natural keys and what Hibernate does with them. In this answer, we will recap the two kinds of keys, map a natural id, load entities by it, see how Hibernate caches the resolution, and look at mutability and database constraints.

1A Quick Recap of Surrogate and Natural Keys

A surrogate key is a value created only to identify the row, usually a sequence number or a UUID. It has no meaning outside the database and never needs to change. A natural key is a value from the business domain that is already unique: the ISBN of a book, a vehicle's VIN, a user's email. Natural keys are what people search by, but they can change, have formats that evolve, or turn out not to be unique after all.

The usual design is to use a surrogate as the primary key, so foreign keys stay stable and small, and to mark the natural key as a unique business identifier. Hibernate's @NaturalId expresses exactly that second role.

2Mapping a Natural Id

We annotate the business key with @NaturalId. Hibernate then knows that this attribute uniquely identifies the entity and, by default, that it never changes.

Java
@Entity
class Book {
@Id @GeneratedValue Long id; // surrogate primary key
@NaturalId
@Column(nullable = false, length = 17)
String isbn; // "978-0-13-468599-1"
String title;
}
// schema generated by Hibernate: unique constraint on book(isbn)

Notice the comment: when Hibernate generates the schema, it adds a unique constraint for the natural id. In production the schema usually comes from Flyway or Liquibase migrations, and there the constraint must be written explicitly. Without it, two concurrent inserts with the same ISBN can both succeed, and the natural id is unique only in our hopes. In the migration we write it ourselves: ALTER TABLE book ADD CONSTRAINT uk_book_isbn UNIQUE (isbn).

3Loading an Entity by Natural Id

The natural id API lives on Hibernate's Session, not on the JPA EntityManager, so we first unwrap the Session. For a single-attribute natural id we use bySimpleNaturalId; for natural ids made of several attributes we use byNaturalId and name each part.

Java
Session session = entityManager.unwrap(Session.class);
Book b = session.bySimpleNaturalId(Book.class).load("978-0-13-468599-1");
// select ... from book where isbn=? -> the Book, or null if none
@Entity class Seat { @Id Long id; @NaturalId String flight; @NaturalId String seatNo; }
Seat s = session.byNaturalId(Seat.class)
.using("flight", "LH 400")
.using("seatNo", "12A")
.load();
// getReference() instead of load() returns a proxy where possible

The result is the same as a JPQL query on isbn, but the API tells Hibernate that we are looking up by a unique key, which is what enables the caching in the next section. Spring Data JPA has no built-in natural id method, so teams usually add a small custom repository fragment that unwraps the Session and calls this API.

4How Hibernate Caches the Resolution

When Hibernate loads or persists a Book, it records in the persistence context that ISBN 978-0-13-468599-1 resolves to id 42. A later natural id lookup in the same session first checks this resolution; if it finds the id and the entity is already loaded, it returns the entity with no SQL at all, just like find() by primary key. A plain JPQL query by isbn cannot do that, because Hibernate does not know the query is a unique key lookup and must run it.

Java
Book a = session.bySimpleNaturalId(Book.class).load("978-0-13-468599-1"); // select ... where isbn=?
Book b = session.bySimpleNaturalId(Book.class).load("978-0-13-468599-1"); // no SQL
System.out.println(a == b); // true
em.createQuery("select b from Book b where b.isbn = :i", Book.class)
.setParameter("i", "978-0-13-468599-1").getSingleResult(); // select runs again
Step throughResolving a natural id
CodePersistence contextDatabase
load by isbn 978-0-13-468599-1
select where isbn = ?
row id 42
remember isbn -> 42
load by the same isbn again
Book 42, no SQL

6 messages in order. Play them, or step through them one at a time.

Across sessions, adding @NaturalIdCache together with the second-level cache keeps the natural id to id mapping in a shared cache, so even new sessions can skip the lookup query and go straight to the entity cache or a primary key select.

5Mutable Natural Ids

By default a natural id is immutable, and Hibernate treats a change to it as an error at flush. Some business keys do change, such as a username or an email. @NaturalId(mutable = true) allows that, but Hibernate then has to check at flush whether the natural id of each managed entity changed and keep its resolution cache in step, which costs extra work, and cached resolutions in other sessions or the second-level cache must be kept consistent. If the key changes often, it is better treated as an ordinary unique column than as a natural id.

Java
@NaturalId(mutable = true)
String email;
user.setEmail("ana@new.com"); // allowed; Hibernate updates its natural id resolution at flush

6Follow-up questions

How do you get the Session from a JPA EntityManager?

Call entityManager.unwrap(Session.class). It returns Hibernate's Session behind the EntityManager, which gives access to Hibernate-only APIs such as natural id loading. In a Spring application the injected EntityManager is a shared proxy, so we call unwrap inside a transaction to get the session bound to it.

Should the natural id be the primary key instead?

Usually not. Primary keys are copied into every foreign key, index and often into other systems, so they should never change and should be compact. Natural keys can change, and their format can grow, as ISBN did from 10 to 13 digits. Keeping a surrogate primary key and a natural id for lookups gives the benefits of both.

Is a natural id a good basis for equals and hashCode?

Yes, when it is assigned at creation and immutable, because it is stable before and after persist, unlike a generated id. That is one of the strongest reasons to map one.

7Conclusion

In this answer, we saw that @NaturalId marks a unique, usually immutable business key next to a surrogate primary key. We loaded entities with bySimpleNaturalId and byNaturalId after unwrapping the Session from the EntityManager, saw that Hibernate caches the natural id to id resolution so a repeated lookup in the same session needs no query, and noted that mutable natural ids cost extra checks and that the unique constraint must be in our migrations because Hibernate only adds it when generating the schema.

What to say in the interviewAbout 90 seconds aloud

Open with

A natural id is a business key that is unique in the domain and usually never changes, like an ISBN, a VIN or an email. In Hibernate I mark it with NaturalId, while the primary key stays a surrogate, like a sequence number, which is what foreign keys use.

Then, if they want more

The two have different jobs: the surrogate is stable and compact for joins, and the natural id is how people look things up. To load by it, I unwrap the Hibernate Session from the EntityManager, entityManager.unwrap of Session.class, and call bySimpleNaturalId of Book.class, then load with the ISBN.

For a key with several attributes, I use byNaturalId and call using for each attribute. The advantage over a JPQL query on the isbn column is caching: Hibernate remembers which id each natural id resolves to, so a second lookup in the same session, or an entity already loaded, comes back without SQL.

With NaturalIdCache and the second-level cache, that resolution can be shared across sessions too. By default the natural id is immutable; NaturalId with mutable true allows changes, but then Hibernate has to check for changes at flush and keep its caches in sync.

And one practical point: Hibernate adds a unique constraint only when it generates the schema, so in a real project I add the unique constraint in the Flyway or Liquibase migration myself.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "What is a Hibernate @NaturalId, and how does it differ from the primary key? Show how to...": https://scrivio-interview-library.netlify.app/databases/jpa-fundamentals/fce5ea8959/