How to Save Data into Database Using Spring Data JPA : Step by Step Tutorial java Spring Spring Boot Spring Data JPA by devs5003 - May 21, 2023May 8, 20243 Last Updated on May 8th, 2024If 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”. Table of Contents Toggle Software UsedStep #1: Creating Starter Project Using STSStep#2 : Writing codes to implement bulk save operationUpdating application.propertiesNew Classes/InterfacesEmployee.java EmployeeRepository.java(Interface)DBOperationRunner.javaStep#3: Running the applicationStep#4: Verify saved records in the DatabaseFAQsCan Spring Boot applications use multiple databases concurrently? 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’. 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. After clicking on ‘Finish’, you will see Project is created in Package Explorer accordingly as shown below. 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. 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—-” . 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. 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/. FAQs 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. Related
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. Reply