Loading Data Into MongoDB With an ApplicationRunner
Learn how to load data into MongoDB with an ApplicationRunner and learn how fluxes work in a blocking programming style.
We'll cover the following
Data loader
By now, we have all the code we need to run our Spring Boot application. However, we don’t have the quotes stored in the database yet. We’ll solve this by reading them from a text version of the book and storing them into MongoDB the first time the application runs.
In the project’s GitHub repository, you’ll see a file containing the ebook in text mode: pg2000.txt
. The first time we run the application, every paragraph will be stored as a quote in MongoDB. To achieve this, we inject an ApplicationRunner
implementation in the application’s context: the QuijoteDataLoader
class.
You can learn more about how the
ApplicationRunner
approach works in the Spring Boot’s reference documentation.
In our case, we’ll first check if the data is already there on line 17
. If it isn’t, we’ll create a Flux from a BufferedReader
stream, and, for each line, we’ll convert it to a Quote
object and store it in the database. For the identifiers, we use a functional Supplier
interface to generate a sequence.
Get hands-on with 1200+ tech skills courses.