1. Project Setup

To start, we need a Maven project with the necessary dependencies. Here’s the pom.xml:

2. Database Configuration

In the application.properties file, configure the database connection and Hibernate settings:

spring.datasource.url=jdbc:mysql://localhost:3306/bootWork
spring.datasource.username=root
spring.datasource.password=root@123
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.batch.jdbc.initialize-schema=always 

3. Model Class: Product

The Product class represents the data model. It includes fields like productId, title, description, price, discount, and discountedPrice, along with their respective getters and setters.

public class Product {
    private int productId;
    private String title;
    private String description;
    private BigDecimal price;
    private BigDecimal discount;
    private BigDecimal discountedPrice;
    // Getters and Setters
} 

4. Configuration Class: BatchConfig

The BatchConfig class is the central configuration for the Spring Batch job. It defines the job, step, reader, processor, and writer.

Job Definition: The jobBean method creates a batch job with a single step.

Step Definition: The step method defines a step that reads, processes, and writes Product data.
Reader: The FlatFileItemReader reads data from product.csv.

Processor: The CustomeItemProcessor processes each Product to calculate the discounted price.

Writer: The JdbcBatchItemWriter writes the processed data to the PRODUCTTS table in the MySQL database

5. Processing Logic: CustomeItemProcessor5. Processing Logic: CustomeItemProcessor

The CustomeItemProcessor class implements the ItemProcessor interface and contains the logic to calculate the discounted price for each product.

6. Job Listener: JobCompletionNotficationImpl6.

This class implements JobExecutionListener to log the status of the job before and after execution.

7. Running the Application

Finally, the BootbatchApplication class runs the Spring Boot application, initiating the batch job.

8. Summary

In this blog, we walked through creating a Spring Batch application that reads product data from a CSV file, processes it to apply discounts, and writes the results into a MySQL database. This application demonstrates the core concepts of Spring Batch, including job configuration, step processing, and data handling with Spring Batch components.