|
This version is still in development and is not considered stable yet. For the latest stable version, please use Spring Data Relational 3.5.5! |
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.
Consider the following entity:
@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:
SELECT nextval('public.my_seq');
The fetched identifier value is included in VALUES during the insert:
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. |