The sequence strategy uses a database sequence to generate the id values. The following sample uses a database sequence named puma_id_seq to generate the id values. For every insert the sequence is called and the value is set as id value.
@Id @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "my_gen") @SequenceGenerator(name = "my_gen", sequenceName = "puma_id_seq", allocationSize = 1) private Integer id;
If we change the allocation size to 50, Hibernate will apply a so-called high-low-algorithm to create the id values. A database sequence of 10 will let Hibernate generate ids from 10x50=500 to 549, a sequence value of 11 from 11x50=550 to 549. This is very useful, because Hibernate only needs to select the next sequence value for every 50teenth insert statement.
@Id @TableGenerator(name = "puma_gen", table = "primary_keys") @GeneratedValue(strategy = GenerationType.TABLE, generator = "puma_gen") private Integer id;
Table 6.4. Id Generator Strategies
Uses a sequence, default name is hibernate_seq, (Oracle PostgreSql and other)
Uses a table to store the latest primary key value (all databases)
Special column type (MS SQL and other)
All these generators are supported by JPA as well. Hibernate adds an extension called GenericGenerator. It allows to use all kind of XML ID generators with annotation as well. Further information to these can be found in our Annotation reference in chapter Annotation Reference the section called “Annotation Reference”.