Spring Batch full example to read from MySQL database using JdbcCursorItemReader and write to a Flat file using FlatFileItemWriter. Optional ItemProcessor to perform business logic/filtering on the input records -.
SPRING BATCH: Write data to a H2 database
WithSpring Batch, you can define and run jobs. The jobs may have a step or many steps.
![Spring boot batch read from database and write to database Spring boot batch read from database and write to database](/uploads/1/2/6/2/126288530/839134359.jpg)
Typically Batch Jobs are long-running, non-interactive and process large volumes of data, more than fits in memory or a single transaction. During a step, the job do something, a particular task, named tasklet. When you define a step you can define the next step you have to execute. A job could execute steps in a defined order.
When you define a step you have 2 models:
![Spring batch read from file and write to database from form 1 Spring batch read from file and write to database from form 1](/uploads/1/2/6/2/126288530/441017018.jpg)
1) run a simple task (tasklet)
2) run a step using the following pattern READ-PROCESS-WRITE
This tutorial explains you how to use the second approach. The first model can be seen when you read the article named 'SPRING BATCH: Create a Step'.
We can have in Spring Batch: sequential steps and parallel steps. We can execute some tasks (steps) when a condition is true or false. Because of these things, you can create workflows using Spring Batch.
For more information related to Spring Batch model you can take a look to the article named 'SPRING BATCH: The Main Concepts'.
In this tutorial you can see how you can read a CSV file and write the content into a H2 database all this in one step. This step follow the pattern READ-PROCESS-WRITE, but in this example I skip the 'PROCESS' activity for creating a simpler example.
In order to create a simple example using the pattern READ-PROCESS-WRITE in Spring Batch, first you have to create a simple Maven Spring project with the pom.xml file having the following dependencies:
At this point it is supposed that the Job Repository has been configured already. Take a look at the article named 'SPRING BATCH: Infrastructure Configuration (Using H2)'.
In order to see how to create a READ-PROCESS_WRITE step, you have to create a batch.properties file with the following content :
and add the following classes:
The registration.csv file has the following content:
In H2 database Console, you have to create the following table:
Now you have to run the Spring application and you can see the following information added into the BATCH.REGISTRATION table from the H2 database:
If you want, you can take a look at the following articles as well : SPRING BATCH: Sequential Steps, SPRING BATCH: Concurrent Steps.
Note:
This article was inspired from the book named 'Spring 5 Recipes: A problem-Solution Approach', Fourth Edition, written by Marten Deinum, Daniel Rubio and Josh Long.