|
| 1 | +[[r2dbc.sequences]] |
| 2 | += Sequences Support |
| 3 | + |
| 4 | +Since Spring Data R2DBC 3.5, properties that are annotated with `@Id` and thus represent |
| 5 | +an Id property can additionally be annotated with `@Sequence`. This signals, that the Id property |
| 6 | +value would be fetched from the configured sequence during an `INSERT` statement. By default, |
| 7 | +without `@Sequence`, the identity column is assumed. Consider the following entity. |
| 8 | + |
| 9 | +.Entity with Id generation from sequence |
| 10 | +[source,java] |
| 11 | +---- |
| 12 | +@Table |
| 13 | +class MyEntity { |
| 14 | + |
| 15 | + @Id |
| 16 | + @Sequence( |
| 17 | + sequence = "my_seq", |
| 18 | + schema = "public" |
| 19 | + ) |
| 20 | + private Long id; |
| 21 | + |
| 22 | + private String name; |
| 23 | +} |
| 24 | +---- |
| 25 | + |
| 26 | +When persisting this entity, before the SQL `INSERT` Spring Data will issue an additional `SELECT` |
| 27 | +statement to fetch the next value from the sequence. For instance, for PostgreSQL the query, issued by |
| 28 | +Spring Data, would look like this: |
| 29 | + |
| 30 | +.Select for next sequence value in PostgreSQL |
| 31 | +[source,sql] |
| 32 | +---- |
| 33 | +SELECT nextval('public.my_seq'); |
| 34 | +---- |
| 35 | + |
| 36 | +The fetched Id would later be included in the `VALUES` list during an insert: |
| 37 | + |
| 38 | +.Insert statement enriched with Id value |
| 39 | +[source,sql] |
| 40 | +---- |
| 41 | +INSERT INTO "my_entity"("id", "name") VALUES(?, ?); |
| 42 | +---- |
| 43 | + |
| 44 | +For now, the sequence support is provided for almost every dialect supported by Spring Data R2DBC. |
| 45 | +The only exception is MySQL, since MySQL does not have sequences as such. |
| 46 | + |
0 commit comments