- Spring Batch Tutorial
Overview In this tutorial, we show you how to create a simple example using Spring Batch Boot to Read XML file and Write to MySQL Database. Configure a Spring Batch Boot using StaxEventItemReader for reading xml data, JdbcBatchItemWriter to write data to mysql database, with spring-oxm maven. In this tutorial, we show you how to configure Spring Batch Boot Job to read information from a CSV file and write to MySQL Database using Eclipse Oxygen Java. Spring Batch Boot to read from MySQL database using JdbcCursorItemReader and write to a Flat file using FlatFileItemWriter.
- Spring Batch Useful Resources
- Selected Reading
In this chapter, we will create a Spring Batch application which uses an MySQL Reader and a Flatfile Writer (.txt ).
Reader − The Reader we are using in the application is JdbcCursorItemReader to read data from MySQL database.
Assume we have created a table in the MySQL database as shown below.
Assume we have inserted the following records into it.
Writer − The Writer we are using in the application is FlatFileItemWriter to write the data to flatfile (.txt).
Processor − The Processor we are using in the application is a custom processor which just prints the records read from the CSV file.
jobConfig.xml
![Read Read](http://websystique.com/wp-content/uploads/2014/08/SpringBatchDatabaseToCsv_img1.png)
Following is the configuration file of our sample Spring Batch application. In this file, we will define the Job and the Steps. In addition to these, we also define the beans for ItemReader, ItemProcessor, and ItemWriter. (Here, we associate them with respective classes and pass the values for the required properties to configure them.)
Context.xml
Following is the context.xml of our Spring Batch application. In this file, we will define the beans like job repository, job launcher, and transaction manager.
CustomItemProcessor.java
Following is the Processor class. In this class, we write the code of processing in the application. Here, we are printing the contents of each record.
TutorialRowMapper.java
Following is the TutorialRowMapper class which sets the data to the Tutorial class.
Tutorial.java
![Spring batch read from file and write to database Spring batch read from file and write to database](http://4.bp.blogspot.com/-wHkj8DOijZY/Vh_TGAPp99I/AAAAAAAABcA/CRlYmIC--co/s1600/Spring%2BBatch%2BExample.png)
Following is the Tutorial class. It is a simple Java class with setter and getter methods. In this class, we are using annotations to associate the methods of this class with the tags of the XML file.
App.java
Following is the code which launces the batch process. In this class, we will launch the Batch Application by running the JobLauncher.
On executing this application, it will produce the following output.
This will generate a .txt file with the following contents.