- • Quickstart
- • Documentation
- • Documentation DevOps
- • Spring Data
- › Spring Data MongoDB
- • Spring REST
- • Frontend
- • Multi-Module
- • IntelliJ Integration
Last updated: 2022-03-20
Generating IDs in Spring Data MongoDB using Sequences
Did you know that you can save days or weeks of development time when starting new Spring Boot apps? br With Bootify you have the right helper at your side - get a runnable prototype in minutes and focus on your business logic instead. Best practices included.
It is often desirable to automatically assign primary keys following a sequence. This article will describe the setup to enable this feature in our Spring Boot application.
In general, we can assign any primary key to our document ourselves. So if we set the id of our document with
setId(...), MongoDB will directly use this value.
Example of assigning a random primary key
To assign the value following a sequence, we first create a collection in which the current value is stored and incremented.
In addition we need a service providing the sequence value. The
getNextValue() method returns and increments the current value and, if necessary, creates the sequence once if it does not already exist. Our sequence here starts at
10000 to reserve values below that for fixed ids.
Finally, we need an EventListener for our document. By linking to
BeforeConvertEvent, a primary key is automatically assigned to our new document before persisting it to MongoDB. With this, our sequence setup is complete and ready to be used.
In the Free plan of Bootify you can create a Spring Boot application for MongoDB. The database schema can be freely defined and the setup including listeners is automatically generated.