Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   




Spring Boot - CRUD operations with Spring Data JPA


Now, that we understood the basics of ORM and JPA in the previous tutorials, let us see how CRUD operations works with Spring Data JPA.


If you are new to CRUD operations, CRUD stands for Create, Read, Update and Delete.


Now, let us try correlating CRUD with SQL statements :

  1. Create Operation :

    Inserts a new record to the database using INSERT statement.

  2. Read Operation :

    Reads records from the database using the SELECT statement.

  3. Update Operation :

    Updates records in a database using the UPDATE statement.

  4. Delete Operation :

    Delete records from a database using the DELETE statement.

Now, let us create our Spring boot application and implement CRUD operations in that.


So, let's go back to the example we have taken in the previous tutorials.


Say, you are the Principal in a reputed School and the School Inspector has visited your school and has come up with a lot of queries.


Now the school Inspector came up with a new query. i.e. All the student details must be saved in a database.


New, you being the Principal of the school, you need to perform below steps to get you Spring Boot JPA code working :


INSERT in Database


The first thing you need to do is, include Spring data jpa starter dependency and the H2 database dependency in pom.xml file.


In our pom.xml file.


Example :




<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>springbootproject</artifactId>
    <version>1.0-SNAPSHOT</version>

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

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>runtime</scope>
        </dependency>

    </dependencies>
</project>




Saving the Student details to database

  1. Since, you are going to save the student details, you need to have a student class,



    public class Student {
    	int roll;
    	String name;
    	int age;
    	int className;
    }

  2. And you need to tell Spring Boot that the contents of this Student class needs to be saved to the database.



    For that, use the @Entity annotation on the Student class.

    @Entity
    public class Student {
    	int roll;
    	String name;
    	int age;
    	int className;
    }


    The @Entity on the Student class tells Spring Boot to save the contents of this Student class to the database.

  3. Now, if you are trying to make a table, there should be a primary key as well. And thanks to Spring Boot as it comes up with an @Id annotation.



    You need to place the @Id annotation on top of the roll attribute.

    @Entity
    public class Student {
    	@Id
    	int roll;
    	String name;
    	int age;
    	int className;
    }


    And the roll attribute will be saved to the database as a primary key.

Now that we are done making the Student class with @Entity and @Id, we would need to tell Spring Boot that it has to perform CRUD operations.


Configuring application.properties for H2 database


As we have seen in previous tutorial, H2 database has the below properties already configured.


spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect

This typically means, we can connect to the H2 database with the username sa and empty password.


spring.datasource.username=sa
spring.datasource.password=

Now, under the resources folder, create the application.properties file and place the database name as testdb and set the spring.h2.console.enabled filed to true. So that we can see the console from web browser.


application.properties


spring.h2.console.enabled=true
spring.datasource.url=jdbc:h2:mem:testdb
Spring Boot - CRUD operations with Spring Data JPA

CRUD operations


To perform CRUD operations, Spring Boot uses a class called CrudRepository.


To implement CrudRepository, all you need to do is,

  1. Create an Interface called StudentRepository,


    Spring Boot - CRUD operations with Spring Data JPA

  2. And make the Interface StudentRepository inherit the CrudRepository class.


    public interface StudentRepository extends CrudRepository {
    }


    Just remember the CrudRepository must have generic values as the Entity class (i.e. Student class) and its Id (i.e. roll of Integer type).
    Spring Boot - CRUD operations with Spring Data JPA

And that's all.


Now, the next thing you need to do is, use the REST API endpoints to INSERT the student details to the database.


To do that let us follow the below steps :

  1. Open POSTMAN, and select the method as POST.


    Spring Boot - CRUD operations with Spring Data JPA

  2. And mention the endpoint


    localhost:8080/students


    This is where we are going to insert the details of the Students.
    Spring Boot - CRUD operations with Spring Data JPA

  3. Now insert the details of John in JSON format.


    {"name": "John", "roll": 1, "age": 8, "className": 5}


    To do that select body -> raw and select JSON from the dropdown
    Spring Boot - CRUD operations with Spring Data JPA


    Now, take the JSON and paste it in POSTMAN,
    Spring Boot - CRUD operations with Spring Data JPA

Once we are done with the above steps in POSTMAN, let us go to the code in Spring Boot.


Spring Boot Code


Let us see the RestController class.


HelloWorldController.class


@RestController
public class HelloWorldController {

	@Autowired
	StudentService studentService;

	@RequestMapping(method = RequestMethod.POST, value = "/students")
	public void insertStudent(@RequestBody Student student) {

		studentService.insertStudentDetails(student);
	}
}
Spring Boot - CRUD operations with Spring Data JPA

So, when we POST the above request from POSTMAN, Spring Boot finds that it is a POST request that is mapped to the endpoint /students(Since the endpoint is localhost:8080/students).


And Spring Boot finds that the method insertStudent(...) method is linked to it.


@RequestMapping(method = RequestMethod.POST, value = "/students")
public void insertStudent(@RequestBody Student student) {

	studentService.insertStudentDetails(student);
}

And StudentService is the class where we perform the actual action of saving the details of John to the database.





Name Roll Age ClassName
John 1 8 5

Now, the StudentService class,


@Service
public class StudentService {

	public void insertStudentDetails(Student student) {
	}
}

Has the method, insertStudentDetails(...),


public void insertStudentDetails(Student student) {
}

Now, to save the details of John, we need to call the StudentRepository interface that extends the CrudRepository class.


public interface StudentRepository extends CrudRepository {
}

So, in StudentService let's Autowire the StudentRepository interface to use it.


@Service
public class StudentService {

	@Autowired
	StudentRepository studentRepository;

	public void insertStudentDetails(Student student) {
	}
}

Then call the save() method of the StudentRepository interface.


@Service
public class StudentService {

	@Autowired
	StudentRepository studentRepository;

	public void insertStudentDetails(Student student) {

		studentRepository.save(student);
	}
}

But have you noticed something weird?


There was no save() method in StudentRepository interface.


public interface StudentRepository extends CrudRepository {
}

Then how did we call the save() method.


studentRepository.save(student);

Well! This is exactly where Spring Data JPA come into picture.


Spring Data JPA makes an intelligent guess to perform CRUD operations(Like save, update, read, delete).


Spring Data JPA gives you the save() method, that you have used to save student details to the database.


studentRepository.save(student);

Now, let us run the Spring Boot Application.


Then open POSTMAN and after entering the details of John,

Spring Boot - CRUD operations with Spring Data JPA

Hit the send button.


And the details of John is saved to the H2 Database.


Now, to check if the details of John is saved or not, let us open the H2 database console.


Follow the below steps to login to H2 database :

  1. Open a web browser and type enter the URL


    http://localhost:8080/h2-console/


    And you would fing the login screen.
    Spring Boot - CRUD operations with Spring Data JPA

  2. Then, click on connect and you would find the below screen.


    Spring Boot - CRUD operations with Spring Data JPA

  3. Now, to check if the details of John saved to H2 database, run the select statement,


    select * from student;

    Spring Boot - CRUD operations with Spring Data JPA


    And you can see that the details of John is already there in the Student table.

Note : Since H2 in an In Memory database, the details of Student will be lost once you close your Spring Boot application.