Video in progress

What does @NaturalId give you, and how do you use it for entities that are frequently looked up by a business key?

@NaturalId tells Hibernate about the business key (tax ID, email, SKU): it is marked as unique and usually immutable, loaded with the Session's byNaturalId API, and the natural id → PK mapping is cached. That way repeated lookups hit the database less.

📖 Answer

In many systems you look up an entity not by the surrogate ID but by a business key: product by SKU, user by email. A plain JPQL query goes to the database every time, and the result does not use the L2 cache.

@Entity
@NaturalIdCache
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
class Product {
    @Id @GeneratedValue Long id;

    @NaturalId
    @Column(nullable = false, unique = true)
    private String sku;
}

Product p = em.unwrap(Session.class)
              .bySimpleNaturalId(Product.class)
              .load("SKU-1042");

What happens:

  • within one Session the second call does not hit the database: the persistence context also looks up by natural id;
  • with @NaturalIdCache the SKU → ID mapping is stored in the L2 cache, and if the entity itself is cached too, no query goes to the database at all;
  • by default a natural id is immutable; if you try to change it, Hibernate throws an error. If it can change, use @NaturalId(mutable = true), but then keeping the cache consistent gets more expensive.

Spring Data has no direct support for this API, so I write a small custom repository fragment.

When you don't need it: if the natural id is rarely used, or the business key can really change (an email, for example: the user can change it). In that case a plain unique index and a query are enough.

Bonus: a @NaturalId field is the best basis for equals/hashCode, because it is known even before persist.