The sequence strategy consists of two parts - defining a named sequence and using the named sequence in one or more fields in one or more classes. The @SequenceGenerator annotation is used to define a sequence and accepts a name, an initial value (the default is 1) and an allocation size (the default is 50). A sequence is global to the application and can be used by one or more fields in one or more classes. The SEQUENCE strategy is used in the @GeneratedValue annotation to attach the given field to the previously defined named sequence:
public class EntityWithSequenceId {
// Use the sequence that is defined above:
@GeneratedValue(strategy=GenerationType.SEQUENCE, generator="seq")
@Id long id;
}
Unlike AUTO and IDENTITY, the SEQUENCE strategy generates an automatic value as soon as a new entity object is persisted (i.e. before commit). This may be useful when the primary key value is needed earlier. To minimize round trips to the database server, IDs are allocated in groups. The number of IDs in each allocation is specified by the allocationSize attribute. It is possible that some of the IDs in a given allocation will not be used. Therefore, this strategy does not guarantee there will be no gaps in sequence values.