This version is still in development and is not considered stable yet. For the latest stable version, please use Spring Data Relational 3.5.0!spring-doc.cn

Sequence Support

Primary key properties (annotated with @Id) may also be annotated with @Sequence. The presence of the @Sequence annotation indicates that the property’s initial value should be obtained from a database sequence at the time of object insertion. The ability of the database to generate a sequence is determined by the used database dialect. In the absence of the @Sequence annotation, it is assumed that the value for the corresponding column is automatically generated by the database upon row insertion.spring-doc.cn

Consider the following entity:spring-doc.cn

Entity with Id generation from a Sequence
@Table
class MyEntity {

    @Id
    @Sequence(
        sequence = "my_seq",
        schema = "public"
    )
    private Long id;

    // …
}

When persisting this entity, before the SQL INSERT, Spring Data will issue an additional SELECT statement to fetch the next value from the sequence. For instance, for PostgreSQL the query, issued by Spring Data, would look like this:spring-doc.cn

Select for next sequence value in PostgreSQL
SELECT nextval('public.my_seq');

The fetched identifier value is included in VALUES during the insert:spring-doc.cn

Insert statement enriched with Id value
INSERT INTO "my_entity"("id", "name") VALUES(?, ?);
Obtaining a value from a sequence and inserting the object are two separate operations. We highly recommend running these operations within a surrounding transaction to ensure atomicity.

Supported Dialects

The following dialects support Sequences:spring-doc.cn

Note that MySQL does not support sequences.spring-doc.cn