Java.Hibernate.Medium.What is @NaturalId and how is it used?

Short Answer

The @NaturalId annotation marks a field as a natural business key → a unique, immutable identifier other than the primary key.
Hibernate allows you to load entities efficiently by natural IDs, caching them separately from the primary key.

🔎 Detailed Explanation

🔹 What is a natural ID?

  • A unique attribute of an entity in the real world, not just a surrogate database ID.
  • Examples:
    • Social security number in a Person.
    • Email address in a User.
    • SKU code in a Product.

🔹 Basic usage

@Entity
public class User {
    @Id
    @GeneratedValue
    private Long id;

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

✅ Here, email is unique and treated as a natural ID by Hibernate.

🔹 Loading entities by natural ID
Hibernate provides the byNaturalId() API:

User user = session.byNaturalId(User.class)
                   .using("email", "alice@example.com")
                   .load();

✅ This lets you query efficiently using the natural ID instead of primary key or JPQL.

🔹 Natural ID caching

  • Hibernate can cache natural IDs separately from primary keys → enabling fast lookups without hitting the database.
  • Enable natural ID cache for an entity:
@NaturalIdCache
@Entity
public class User { ... }

🔹 Composite natural IDs
Hibernate supports natural IDs composed of multiple fields:

@NaturalId
private String countryCode;

@NaturalId
private String passportNumber;

🔹 Important notes
✅ Natural IDs should be immutable → changing them can cause cache inconsistency.
✅ Hibernate throws an exception if you modify a natural ID after persisting the entity.

📊 Why use @NaturalId?

✅ Express business-meaningful unique identifiers directly in your domain model.
✅ Enable fast, type-safe entity retrieval by attributes other than the primary key.
✅ Reduce boilerplate JPQL queries like from User where email = :email.

📌 Key Takeaways

@NaturalId maps business keys → unique, immutable fields identifying entities.
✅ Use session.byNaturalId() to retrieve entities efficiently by natural ID.
✅ Combine with @NaturalIdCache for high-performance lookups.

This entry was posted in Без рубрики. Bookmark the permalink.

Leave a Reply

Your email address will not be published.