0% found this document useful (0 votes)
9 views14 pages

Spring Boot - Read CSV Data

Uploaded by

Vin Diesel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views14 pages

Spring Boot - Read CSV Data

Uploaded by

Vin Diesel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

Spring Boot- Read CSV Data or How to read or upload data from CSV file

into MySQL database.

Business Requirement-
Suppose you have one csv file which contain employee data and want to upload
that file data into database, in that case you should go with spring boot with
read CSV data.

Table Structure

Employee Table

Id(PK)

Name

City

Problem Statement
Design the REST API or Restful web service to fetch the data from CSV file and
store it into MySQL database.

Steps-

Create the spring boot project.

Add Maven dependencies into pom.xml file


Create Model class

Create Service

Create Service Implementation

Create Repository
Create Rest Controller

Create CommonUtil

Create ResponseMessage

Application.properties file

Run Spring Boot Application

Open Postman (Request and Response)

Go to Database and Check details

Application Flow

SPRING BOOT- READ CSV DATA BY JEEVAN SIR 1


Project Structure

Step-1- Create Spring boot maven project

File-> New-> Spring Starter Project-> Enter the name and Artifact then

Click on Next button-> Next button-> click on finish button

Step-2- Add maven dependency into pom.xml file

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.1.5</version>

SPRING BOOT- READ CSV DATA BY JEEVAN SIR 2


<relativePath />
</parent>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-properties-
migrator</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>jakarta.persistence</groupId>
<artifactId>jakarta.persistence-api</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate.orm</groupId>
<artifactId>hibernate-core</artifactId>
<version>6.1.4.Final</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</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>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>

SPRING BOOT- READ CSV DATA BY JEEVAN SIR 3


<optional>true</optional>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.33</version>
</dependency>

<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-csv</artifactId>
<version>1.8</version>
</dependency>

Step-3- Create Model Classes

Employee.Java

package com.velocity.model;

import jakarta.persistence.Entity;

import jakarta.persistence.GeneratedValue;

import jakarta.persistence.GenerationType;

import jakarta.persistence.Id;

import jakarta.persistence.Table;

@Entity

@Table(name = "employee")

public class Employee {

// id, name, city

@Id
SPRING BOOT- READ CSV DATA BY JEEVAN SIR 4
@GeneratedValue(strategy = GenerationType.IDENTITY)

private int id;

private String name;

private String city;

public Employee() {

public Employee(int id, String name, String city) {

super();
this.id = id;

this.name = name;

this.city = city;

public int getId() {

return id;

public void setId(int id) {

this.id = id;

public String getName() {

return name;

SPRING BOOT- READ CSV DATA BY JEEVAN SIR 5


public void setName(String name) {

this.name = name;

public String getCity() {

return city;

public void setCity(String city) {

this.city = city;

@Override

public String toString() {

return "Employee [id=" + id + ", name=" + name + ", city=" + city


+ "]";

Step-4- Create Service

EmployeeService.Java
package com.velocity.service;
import org.springframework.web.multipart.MultipartFile;

public interface EmployeeService {

public void save(MultipartFile file);


}

Step-5-Service Implementation

EmployeeServiceImpl.Java
SPRING BOOT- READ CSV DATA BY JEEVAN SIR 6
package com.velocity.service.impl;

import java.io.IOException;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;

import org.springframework.web.multipart.MultipartFile;

import com.velocity.model.Employee;

import com.velocity.repository.EmployeeRepository;

import com.velocity.service.EmployeeService;

import com.velocity.util.CommonUtil;

@Service

public class EmployeeServiceImpl implements EmployeeService {

@Autowired

private EmployeeRepository employeeRepository;

@Override
public void save(MultipartFile file) {

try {

List<Employee> employees =
CommonUtil.csvToEmployees(file.getInputStream());

employeeRepository.saveAll(employees);

} catch (IOException e) {
throw new RuntimeException("fail to store csv data: " +
e.getMessage());

SPRING BOOT- READ CSV DATA BY JEEVAN SIR 7


}

Step-6-Create Repository

EmployeeRepository.Java

package com.velocity.repository;

import org.springframework.data.jpa.repository.JpaRepository;

import org.springframework.stereotype.Repository;

import com.velocity.model.Employee;

@Repository
public interface EmployeeRepository extends
JpaRepository<Employee,Integer>{

Step-7- Create Rest Controller


EmployeeController.Java

package com.velocity.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;

import org.springframework.http.ResponseEntity;

import org.springframework.web.bind.annotation.PostMapping;

import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import org.springframework.web.multipart.MultipartFile;

import com.velocity.service.EmployeeService;

import com.velocity.util.CommonUtil;

import com.velocity.util.ResponseMessage;

SPRING BOOT- READ CSV DATA BY JEEVAN SIR 8


@RestController

public class EmployeeController {

@Autowired

private EmployeeService employeeService;

@PostMapping("/upload")

public ResponseEntity<ResponseMessage>
uploadFile(@RequestParam("file") MultipartFile file) {

String message = "";

if (CommonUtil.hasCSVFormat(file)) {

try {

employeeService.save(file);

message = "Uploaded the file successfully: " +


file.getOriginalFilename();

return
ResponseEntity.status(HttpStatus.OK).body(new ResponseMessage(message));

} catch (Exception e) {
message = "Could not upload the file: " +
file.getOriginalFilename() + "!";
return
ResponseEntity.status(HttpStatus.EXPECTATION_FAILED).body(new
ResponseMessage(message));

message = "Please upload a csv file!";


return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new
ResponseMessage(message));
}

SPRING BOOT- READ CSV DATA BY JEEVAN SIR 9


}

Step-8- Create CommonUtil

CommonUtil.Java

package com.velocity.util;

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStream;

import java.io.InputStreamReader;

import java.util.ArrayList;

import java.util.List;

import org.apache.commons.csv.CSVFormat;

import org.apache.commons.csv.CSVParser;

import org.apache.commons.csv.CSVRecord;

import org.springframework.web.multipart.MultipartFile;

import com.velocity.model.Employee;

public class CommonUtil {

public static String TYPE = "text/csv";

static String[] HEADERs = { "id", "name", "city" };

public static boolean hasCSVFormat(MultipartFile file) {

if (!TYPE.equals(file.getContentType())) {

return false;

SPRING BOOT- READ CSV DATA BY JEEVAN SIR 10


}

return true;

public static List<Employee> csvToEmployees(InputStream is) {


try (BufferedReader fileReader = new BufferedReader(new
InputStreamReader(is, "UTF-8"));

CSVParser csvParser = new CSVParser(fileReader,

CSVFormat.DEFAULT.withFirstRecordAsHeader().withIgnoreHeaderCase().
withTrim());) {

List<Employee> employees = new ArrayList<Employee>();

Iterable<CSVRecord> csvRecords = csvParser.getRecords();

for (CSVRecord csvRecord : csvRecords) {


Employee emp = new
Employee(Integer.parseInt(csvRecord.get("id")), csvRecord.get("name"),

csvRecord.get("city"));

employees.add(emp);
}

return employees;

} catch (IOException e) {
throw new RuntimeException("fail to parse CSV file: " +
e.getMessage());

SPRING BOOT- READ CSV DATA BY JEEVAN SIR 11


}

Step-9- Create ResponseMessage

ResponseMessage.Java

package com.velocity.util;

public class ResponseMessage {

private String message;

public ResponseMessage(String message) {


this.message = message;
}

public String getMessage() {


return message;
}

public void setMessage(String message) {


this.message = message;
}
}

Step-10- Application.properties file

#MysqL
server.port=8181
spring.datasource.driver-class-
name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test?aut
oReconnect=true&useSSL=false

spring.datasource.username=root
spring.datasource.password=root
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dial
ect.MySQL8Dialect

#we can mention maximum excel file size here


spring.servlet.multipart.max-file-size=10 MB

SPRING BOOT- READ CSV DATA BY JEEVAN SIR 12


Step-11- Run Spring Boot Application

Right click on SpringBootApplication-> Run as-> Spring Boot Application.

Step-12-Open Postman (Request and Response)

Request

Select method as Post


Enter the URL as http://localhost:8181/Upload
Select Body->form-data- write file as key and upload file as value
Click on Send button

Response

Step-11- Go to Database and Check details

Employee table

SPRING BOOT- READ CSV DATA BY JEEVAN SIR 13


Step-12- Application Flow

Postman Request (http://localhost:8181/upload) ->


Model Class->RestController->Service->Service Implementation->Repository-
>Database

SPRING BOOT- READ CSV DATA BY JEEVAN SIR 14

You might also like