Hibernate / Hibernate 7 Basics Interview Questions
What is the @NaturalId feature in Hibernate 7 and what is @NaturalIdClass?
A natural ID is a business-meaningful unique identifier distinct from the surrogate PK. Hibernate 7 adds @NaturalIdClass for composite natural IDs.
@Entity public class Book { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) private Long id; // surrogate PK (internal) @NaturalId // business identifier (external) @Column(unique=true, nullable=false) private String isbn; private String title; } // Optimised lookup (uses L2 cache): Book book = session.byNaturalId(Book.class) .using("isbn", "978-0-13-468599-1").load(); // @NaturalIdClass: COMPOSITE natural IDs (NEW in Hibernate 7) public class EmployeeNaturalId { String companyCode; String employeeNumber; // equals() and hashCode() required } @Entity @NaturalIdClass(EmployeeNaturalId.class) // NEW in Hibernate 7 public class Employee { @Id @GeneratedValue private Long id; @NaturalId String companyCode; @NaturalId String employeeNumber; private String name; } // Lookup by composite natural ID: Employee emp = session.byNaturalId(Employee.class) .using("companyCode", "ACME") .using("employeeNumber", "EMP-001").load();
More Related questions...