You are here
Home > java >

How to Save Data into Database Using Spring Data JPA : Step by Step Tutorial

How to Save Data into Database Using Spring Data JPA : Step by Step TutorialIf we are developing a project using Spring Boot, we take help of Spring Data JPA to solve our database operations need. In this article we will go through โ€œHow to Save Data into Database Using Spring Data JPA : Step by Step Tutorialโ€. If we are developing a project using Spring boot, saving data into the database is the mandatory topic to learn. Furthermore, we will go through step by step in this article. Also, we will save bulk data in a batch. Now letโ€™s start our exercise as โ€œHow to Save Data into Database Using Spring Data JPA : Step by Step Tutorialโ€.

Software Used

โ™ฆ STS (Spring Tool Suite) : (download link: https://spring.io/tools)
โ™  MySQL Database
โ™ฆ JDK 8 (Extremely Tested on JDK9, JDK11, JDK 14 & JDK15)

Step #1: Creating Starter Project Using STS

In order to create a Spring Boot Starter Project, we will use STS (Spring Tool Suite). Open your STS and go to File >> New >> Spring Starter Project -> Then enter your project name in the Name field as shown below. Itโ€™s โ€œSpringBootDataJPAwithMySQLโ€ in my case as shown below in the screenshot. Next, enter the value of Group field which will become the parent package name of your src folder. Then click on โ€˜Nextโ€™.

Saving Data into Database Using Spring Boot-Data JPA: Step by Step Tutorial

ย 

Since we are going to save data into our MySQL database, we need to add some starter dependencies in our project. These dependencies are nothing but required dependent jars. Spring Boot offers some small starter projects/modules to support these dependencies. Hence, we have to select dependent starter projects which are already provided by Spring boot. Search MySQL string in Available field. Select โ€˜MySQL Driverโ€™ from the results. Additionally, search JPA string in Available field. Then select โ€˜Spring Data JPAโ€™ from the results. Now make sure that both selected modules came under Selected field.

In case you selected wrong module, you can cancel it by clicking on cross sign at Selected field. Then click on โ€˜Finishโ€™. Here selected modules (dependent projects) will be added into pom.xml as a dependency & all required jars will get downloaded automatically. Needless to say, โ€˜MySQL Driverโ€™ and โ€˜Spring Data JPAโ€™ are the dependencies to support database operations using MySQL DB.

Saving Data into Database Using Spring Boot-Data JPA: Step by Step Tutorial

After clicking on โ€˜Finishโ€™, you will see Project is created in Package Explorer accordingly as shown below.Saving Data into Database Using Spring Boot-Data JPA: Step by Step Tutorial

Step#2 : Writing codes to implement bulk save operation

In order to implement our functionality, we will update application.properties file & write 2 new classes & 1 interface to implement our functionality.

Updating application.properties

Here, we will update application.properties file mainly for database properties accordingly as below.

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/mytestdb
spring.datasource.username=root
spring.datasource.password=devs
spring.jpa.database-platform=org.hibernate.dialect.MySQL8Dialect
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update

New Classes/Interfaces

We will create new files under our package โ€˜com.dev.springboot.dataJpaโ€™. Since it is very small functionality & for testing purpose only, briefly, we will create all classes & interfaces in a single package only. But in real time project we should create separate packages for different purpose accordingly.

We will create 2 new classes & one Interface as below.

Employee.javaย 

We will create an Entity class that will map to DB table. It will have all the required fields, getters/setters & constructors annotated with @Entity as below.

package com.dev.springboot.dataJpa;

import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class Employee {

   @Id
   private Integer empId;
   private String empName;
   private Double empSal;
   private String empDept;

   public Employee() {

   }

   public Employee(Integer empId, String empName, Double empSal, String empDept) {
      super();
      this.empId = empId;
      this.empName = empName;
      this.empSal = empSal;
      this.empDept = empDept;
   }

   public Integer getEmpId() {
      return empId;
   }
   public void setEmpId(Integer empId) {
      this.empId = empId;
   }
   public String getEmpName() {
      return empName;
   }
   public void setEmpName(String empName) {
      this.empName = empName;
   }
   public Double getEmpSal() {
      return empSal;
   }
   public void setEmpSal(Double empSal) {
      this.empSal = empSal;
   }
   public String getEmpDept() {
      return empDept;
   }
   public void setEmpDept(String empDept) {
      this.empDept = empDept;
   }

}


โ™ฅ Note : You can still minimize the boilerplate code from this Entity class if you use Lombok API. Further the above class code will reduce to its minimum as below. If you are not familiar with applying Lombok, kindly visit our internal article on Lombok.

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity
public class Employee {

ย  ย  ย @Id
ย  ย  ย private Integer empId;
ย  ย  ย private String empName;
ย  ย  ย private Double empSal;
ย  ย  ย private String empDept;

}

EmployeeRepository.java(Interface)

An interface which extends from JpaRepository<Employee,Integer>. JpaRepository has multiple DB operation methods. For bulk save operation, we will use method saveAll () which will return All Employee data as a List without declaring it in our EmployeeRepository. Of course, this method will be available in our EmployeeRepository through inheritance only.

package com.dev.springboot.dataJpa;

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

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

}

DBOperationRunner.java

This is a Runner class with run() method similar to a thread which is used to run a functionality only once. In fact, It implements CommandLineRunner interface provided by Spring boot. DBOperationRunner class will have @Component so that Spring container creates object of it & our functionality can be run. Further, we will autowire EmployeeRepository via @Autowired in this class so that we can use saveAll() method from the EmployeeRepository interface through JpaRepository.

package com.dev.springboot.dataJpa;

import java.util.Arrays;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

@Component
public class DBOperationRunner implements CommandLineRunner {

  ย  ย @Autowired
  ย  ย EmployeeRepository eRepo;

ย  ย  ย @Override
ย  ย  ย public void run(String... args) throws Exception {

ย  ย  ย  ย  ย  ย eRepo.saveAll(Arrays.asList(

ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  new Employee(1001,"James",2599.5,"HR"),
ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  new Employee(1002,"Elizabeth",2999.0,"Admin"),
ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  new Employee(1003,"Robert",2699.5,"Testing"),
ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  new Employee(1004,"Victoria",3000.5,"Development"),
ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  new Employee(1005,"David",2650.5,"QA"),
ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  new Employee(1006,"Isabel",2590.0,"Support"),
ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  new Employee(1007,"Michael",3599.75,"Development"),
ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  new Employee(1008,"Maria",2499.0,"Finance"),
ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  new Employee(1009,"Thomas",2799.25,"HR"),
ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  new Employee(1010,"Maria",2899.5,"Development"))

ย  ย  ย  ย  ย  ย  ); 

ย // *** Below method List.of(....) will work for JDK 9 onwards***
 // It will not work in Java 8

     /*  ย  ย eRepo.saveAll(List.of(

ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  new Employee(1001,"James",2599.5,"HR"),
ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  new Employee(1002,"Elizabeth",2999.0,"Admin"),
ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  new Employee(1003,"Robert",2699.5,"Testing"),
ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  new Employee(1004,"Victoria",3000.5,"Development"),
ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  new Employee(1005,"David",2650.5,"QA"),
ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  new Employee(1006,"Isabel",2590.0,"Support"),
ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  new Employee(1007,"Michael",3599.75,"Development"),
ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  new Employee(1008,"Maria",2499.0,"Finance"),
ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  new Employee(1009,"Thomas",2799.25,"HR"),
ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  new Employee(1010,"Maria",2899.5,"Development"))

ย  ย  ย  ย  ย  ย );ย  ย  ย */

ย  ย  ย  ย  ย  System.out.println("----------All Data saved into Database----------------------");
ย  ย  ย  ย  ย  }

}

After creating all the files, at last your project structure should look like below screenshot.

Saving Data into Database Using Spring Boot-Data JPA: Step by Step Tutorial

Step#3: Running the application

In the end, to run the application right click on the project and then select โ€œRun Asโ€™ >> โ€˜Spring Boot Appโ€™. Simultaneously, observe the console to see database queries(something like below screenshot) & message โ€œโ€”All Data saved into Databaseโ€”-โ€ .

Console Result

Step#4: Verify saved records in the Database

Open MySQL database software, select database โ€˜mytestdbโ€™ and then execute the query โ€˜SELECT * FROM EMPLOYEEโ€™. You will see the below output immediately.

DB output

Thatโ€™s it. How Simple is that in Spring Boot !. For More details on Spring Data JPA, kindly visit spring.io.

Furthermore, for trending hands-on topics on Spring Boot kindly visit https://javatechonline.com/spring-boot/ and https://javatechonline.com/blogs/.

FAQ

Can Spring Boot applications use multiple databases concurrently?

Yes, Spring Boot permits us to configure and work with multiple data sources in the same application. Spring Boot provides the flexibility to configure and work with multiple databases within the same application.

ย 

3 thoughts on โ€œHow to Save Data into Database Using Spring Data JPA : Step by Step Tutorialโ€

  1. Thank u sir you make this article /information is very useful for us . and what you given its step by step and easy to understand. please keep it up for us. please make video for how to prepare for java developer interview . we want exact path bcz on youtube lots of video are there but no one given that right track.so please make that.

Leave a Reply


Top