Sequence Generation
The sequence generation mechanism enables obtaining unique numerical values via a single API, independent of the DBMS type.
The entry point to this mechanism is the Sequences
interface which can be injected to a bean or a screen:
@Autowired
private Sequences sequences;
Now you can use the createNextValue()
method to generate the next number in the sequence passed as the parameter:
Long nextNumber = sequences.createNextValue(Sequence.withName("some_seq"));
The Sequences
interface provides the following methods:
-
createNextValue()
– returns the next value in a sequence. The mechanism enables simultaneous management of several sequences, identified by arbitrary strings. The name of the sequence from which you want to retrieve the value is passed in theSequence.withName()
static method.Sequences do not require initialization. When
createNextValue()
is called for the first time, the corresponding sequence will be created, and the default value1
will be returned. -
getCurrentValue()
– returns the current value of the sequence. -
setCurrentValue()
– sets the new current value for the sequence. Next time, when you callcreateNextValue()
for this sequence, it will return this value + increment. -
deleteSequence()
– removes the sequence with specified identifier.
The implementation of the sequence generation mechanism depends on the DBMS type. The supported types are HSQL, Microsoft SQL Server, MySQL, Oracle, and PostgreSQL. Sequence parameters can also be managed directly in the database by the rules of the particular DBMS.
The Sequences implementation is based on database sequences or autoincrement fields and does not guarantee a continuous sequence without gaps, it guarantees only the uniqueness of the values. Gaps may happen due to an error or a transaction rollback.
|
Sequence Usage Example
Each Sequence
instance is characterized by the name, the data store, the start value, and the incremental step. You can use setters to define these parameters when calling the methods mentioned above, for example:
@Autowired
private Sequences sequences;
@Autowired
private InstanceContainer<Document> documentDc;
@Subscribe(target = Target.DATA_CONTEXT)
public void onPreCommit(DataContext.PreCommitEvent event) {
Long number = sequences.createNextValue(Sequence.withName("document_number") (1)
.setStore("additional") (2)
.setStartValue(10) (3)
.setIncrement(10)); (4)
documentDc.getItem().setNumber(number);
}
1 | Generates new value of the document_number sequence. |
2 | Points the Sequence to use the additional data store by its name. If not set, the main data store is used. |
3 | Sets the start number of document_number . If not set, the sequence starts with 1 . |
4 | Defines the incremental step of the sequence. If not set, the increment is 1 . |