Import Data from CSV File to Database using Spring Batch
This guide shows how to import data from a CSV file into an Oracle database using Spring Batch. We’ll walk through the setup including dependencies, configurations, a REST controller to launch the job, and working example code.
🧩 Maven Dependencies
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-batch</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.oracle.database.jdbc</groupId>
<artifactId>ojdbc11</artifactId>
<scope>runtime</scope>
</dependency>
⚙️ application.properties
spring.application.name=CSVToDatabase
spring.datasource.url=ADD_URL_HERE
spring.datasource.username=ADD_USERNAME
spring.datasource.password=ADD_PASSWORD
spring.datasource.driver-class-name=oracle.jdbc.OracleDriver
spring.batch.job.enabled=false
🏢 Database Table
CREATE TABLE EMPLOYEE (
ID NUMBER PRIMARY KEY,
NAME VARCHAR2(255),
EMAIL VARCHAR2(255)
);
CREATE SEQUENCE emp_id_seq START WITH 1 INCREMENT BY 1;
📁 Sample CSV File
Save the CSV file as E://exported-files//employee.csv
with the structure:
name,email
John Doe,john@example.com
Jane Smith,jane@example.com
🧱 Employee Entity
@Entity
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "emp_id_seq")
@SequenceGenerator(name = "emp_id_seq", sequenceName = "emp_id_seq", allocationSize = 1)
private Long id;
private String name;
private String email;
// Getters and Setters
}
⚙️ Spring Batch Configuration
@Configuration
public class SpringBatchConfig {
@Autowired
private JobRepository repository;
@Autowired
private PlatformTransactionManager platformTransactionManager;
@Autowired
private EntityManagerFactory entityManagerFactory;
@Bean
public Job csvToDBJob() {
return new JobBuilder("csv-to-db-job", repository)
.incrementer(new RunIdIncrementer())
.start(cvsToDBStep())
.build();
}
@Bean
public Step cvsToDBStep() {
return new StepBuilder("csv-to-db", repository)
.<Employee, Employee>chunk(5, platformTransactionManager)
.reader(flatFileItemReader())
.writer(jpaItemWriter())
.build();
}
@Bean
public JpaItemWriter<Employee> jpaItemWriter() {
JpaItemWriter<Employee> writer = new JpaItemWriter<>();
writer.setEntityManagerFactory(entityManagerFactory);
return writer;
}
@Bean
public FlatFileItemReader<Employee> flatFileItemReader() {
return new FlatFileItemReaderBuilder<Employee>()
.name("flat-file-item-reader-1")
.linesToSkip(1)
.resource(new FileSystemResource("E://exported-files//employee.csv")) //CHANGE PATH IF REQUIRED BASED ON YOUR CSV FILE LOCATION
.delimited()
.names("name", "email")
.targetType(Employee.class)
.build();
}
}
🚀 REST API to Trigger the Batch Job
@RestController
@RequestMapping("job-launcher")
public class JobLauncherController {
@Autowired
private Job job;
@Autowired
private JobLauncher jobLauncher;
@GetMapping("launch-csv-to-db-job")
public String launchCSVToDBJob() throws JobInstanceAlreadyCompleteException,
JobExecutionAlreadyRunningException,
JobParametersInvalidException,
JobRestartException {
JobParameters jobParameters = new JobParametersBuilder()
.addLong("time", System.currentTimeMillis())
.toJobParameters();
jobLauncher.run(job, jobParameters);
return "Job Launched.";
}
}
📌 Endpoint
To trigger the job, send a GET request to:
http://localhost:8080/job-launcher/launch-csv-to-db-job
✅ Summary
In this guide, you learned how to:
- Configure Spring Batch to import CSV data
- Map CSV to a JPA Entity
- Write data to an Oracle database
- Expose a REST endpoint to manually trigger the job
This approach is useful for building powerful data import jobs, especially in enterprise apps where batch processing is a common requirement.
In the next part of this series, we explore how to validate CSV data using an ItemProcessor. Click here to read it.
📺 Want to learn Spring with hands-on videos?
Subscribe to our YouTube channel: Spring Java Lab for practical tutorials on Spring Batch, Boot, and more!
Subscribe to our YouTube channel: Spring Java Lab for practical tutorials on Spring Batch, Boot, and more!