2.13.5.1. Sequence Generator

Most databases allow you to create native sequences. These are database structures that generate increasing numeric values. The SequenceGenerator annotation represents a named database sequence. You can place the annotation on any package, entity class, persistent field declaration (if your entity uses field access), or getter method for a persistent property (if your entity uses property access). SequenceGenerator has the following properties:

  • String name: The generator name. This property is required.

  • String sequenceName: The name of the database sequence. If you do not specify the database sequence, your vendor will choose an appropriate default.

  • int initialValue: The initial sequence value.

  • int allocationSize: The number of values to allocate in memory for each trip to the database. Allocating values in memory allows the JPA runtime to avoid accessing the database for every sequence request. This number also specifies the amount that the sequence value is incremented each time the sequence is accessed. Defaults to 50.

  • String schema: The sequence’s schema. If you do not name a schema, JPA uses the default schema for the database connection.

Note

OpenJPA allows you to use one of OpenJPA’s built-in generator implementations in the sequenceName property. You can also set the sequenceName to system to use the system sequence defined by the openjpa.Sequence configuration property. See the Reference Guide’s Generators for details.

The XML element for a sequence generator is sequence-generator. Its attributes mirror the above annotation’s properties:

  • name

  • sequence-name

  • initial-value

  • allocation-size

  • schema

To use a sequence generator, set your GeneratedValue annotation’s strategy property to GenerationType.SEQUENCE, and its generator property to the sequence generator’s declared name. Or equivalently, set your generated-value XML element’s strategy attribute to SEQUENCE and its generator attribute to the generator name.