Annotation Type NaturalId


  • @Target({METHOD,FIELD})
    @Retention(RUNTIME)
    public @interface NaturalId
    Specifies that a field or property of an entity class is part of the natural id of the entity. This annotation is very useful when the primary key of an entity class is a surrogate key, that is, a system-generated synthetic identifier, with no domain-model semantics. There should always be some other field or combination of fields which uniquely identifies an instance of the entity from the point of view of the user of the system. This is the natural id of the entity.

    A natural id may be a single field or property of the entity:

     @Entity
     @Cache @NaturalIdCache
     class Person {
    
         //synthetic id
         @GeneratedValue @Id
         Long id;
    
         @NotNull
         String name;
    
         //simple natural id
         @NotNull @NaturalId
         String ssn;
    
         ...
     }
     

    or it may be a composite value:

     @Entity
     @Cache @NaturalIdCache
     class Vehicle {
    
         //synthetic id
         @GeneratedValue @Id
         Long id;
    
         //composite natural id
    
         @Enumerated
         @NotNull @NaturalId
         Region region;
    
         @NotNull @NaturalId
         String registration;
    
         ...
     }
     

    Unlike the primary identifier of an entity, a natural id may be mutable().

    On the other hand, a field or property which forms part of a natural id may never be null, and so it's a good idea to use @NaturalId in conjunction with the Bean Validation @NotNull annotation or @Basic(optional=false).

    The Session interface offers several methods that allow an entity instance to be retrieved by its simple or composite natural id value. If the entity is also marked for natural id caching, then these methods may be able to avoid a database round trip.

    See Also:
    NaturalIdCache
    • Optional Element Summary

      Optional Elements 
      Modifier and Type Optional Element Description
      boolean mutable
      Specifies whether the natural id is mutable or immutable.
    • Element Detail

      • mutable

        boolean mutable
        Specifies whether the natural id is mutable or immutable.
        Returns:
        false (the default) indicates it is immutable; true indicates it is mutable.
        Default:
        false