January 13, 2021

Spring Boot – CRUD Operation with JPA Repository

In this chapter, we are going to learn how to make CRUD operation using JPA repository.  As mentioned before, the repository provides methods to perform these operations.The only file we need to modify is the StudentService file.

 

  1. Modify the Repository
  2. Autowire the Repository into the Service
  3. Get List of Students
  4. Add a Student
  5. Get Student by Id
  6. Update a Student Record
  7. Delete a Student
  8. Build the StudentController class
  9. Handling Errors

 

 

1. Modify the Repository

Let’s open the StudentRepository and make a little change. We should actually have done this in the previous chapter. The modified class is shown below.

 

package com.kindsonthegenius.social.student;

import org.springframework.data.repository.CrudRepository;

public interface StudentRepository extends CrudRepository<Student, String> {

}

 

Note the we have provided the Student and String.The Student is the entity type while the String is the primary key type.

 

 

2. AutoWire the Repository into the Service

The very first step is to AutoWire the StudentRepository into the Student Service. So open the StudenRepository class. Create a private member variable of StudentReposiory. Then add @Autowired to this variable. If you do this, the StudentService class would be as shown below:

 

package com.kindsonthegenius.social.student;

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

@Service
public class StudentService {
	
	@Autowired
	public StudentRepository studentRepository;
	
    // The Crud methods goes here
}

 

 

3. Get List of Students

First, we get a list of Students. To do that we use the findAll() method.So this means that we can use a single line as shown below to get all records.

 

studentRepository.findAll();

 

This one line is all is needed to connect to do the following:

  • connect to the database
  • run a query to get all the Student records
  • convert each of the returned rows to Student instances
  • return it back to the service

The findAll() method returns an iterable. So we need to convert it into a list. The complete code is given below:

 

public List<Student> getAllStudents() {
	
    List<Student> students = new ArrayList<>();
	
    studentRepository.findAll()
    .forEach(students::add);
	
    return students;		
}

 

What we do here is that we created an empty list of Student. Then we iterate through the list returned by findAll(). For each item in the list, we add it to the students list we created. We have used a method reference here (::). We could actually test this method now. However, we’ve not populated our controller class. Besides, there is nothing in the database. So we would have an empty result. So the next thing to do is to add a method to add new Student.

 

 

4. Add a Student

To add a new Student is really easy. You do this by using the StudentRepository save() method. You simply pass it as parameter, the Student instance you want to save.

The method is given below.

 

public void addStudent(Student student) {
     studentRepository.save(student);
}

 

 

5. Get Student by Id

Again, the StudentRepository provides a method findById(). This methods takes the id of the Student to find. This method use to be findOne(). But since Spring data jpa 2.0 it’s changed to findById(). Also note the Optional keword. This is there to prevent nullPointerException in case the record is not found.

The code snipped is given below:

 

public Optional<Student> getStudent(String id) {
     return studentRepository.findById(id);
}

 

 

6. Update a Student

To update a Student record, we used the same save() method as with adding a new Student.

 

public void updateStudent(String id, Student student) {
     studentRepository.save(student);
}

 

This is what happens with update: if the record exists, then it is updates. If however, the record with the id does not exist, then it adds a new record.

 

 

7. Delete a Student

To delete a Student record, you simply use the deleteById() method provided by the StudentRepository. The you pass in the id of the record you want to delete.

The code is given below:

 

public void deleteStudent(String id) {
     studentRepository.deleteById(id);
}

 

 

8. Build the Controller Class

Now we are going to write out controller methods in the controller class. It is fairly easy. It’s exacly similar to the other controllers we’ve written. So I would just provide you with the code as shown below:

 

@RestController
public class StudentController {
	
	@Autowired
	private StudentService studentService;

	 @RequestMapping(value = "/students")
	   public List<Student> getAllStudents() 
	   {		
		return studentService.getAllStudents();
	   }	
	 
	 
	 @RequestMapping(value = "/students/{id}")
	 public Optional<Student> getStudent(@PathVariable String id) {
	 	return studentService.getStudent(id);
	 }
	 
	 
	 @RequestMapping(value = "/students", method=RequestMethod.POST)
	 public void addStudent(@RequestBody Student student) {
		 studentService.addStudent(student);
	 }
	 
	 @RequestMapping(value = "/students/{id}", method = RequestMethod.PUT)
	 public void updateStudent(@RequestBody Student student,@PathVariable String id ) {
		 studentService.updateStudent(id, student);
	 }
	 
	 @RequestMapping(value = "/students/{id}", method = RequestMethod.DELETE)
	 public void deleteStudent(@PathVariable String id) {
		 studentService.deleteStudent(id);
		 	 
	 }
}

 

Note that the code above does not include the import statements and package name. So remember to add them.

Now is time to test everything. So open Advanced Rest Client. Add a few student record. The make GET, UPDATE and DELETE requests to see how it works.

 

9. Handling Errors

If you follow these procedures correctly, you may receive some errors. To handle them do the following

 

add a default constructor

Open the Student class and add a default empty constructor. As shown below:

 

public Student() {
    //nothing goes here
}

 

modify the properties file

Open the application.properties file and add the following line:

 

spring.jpa.hibernate.ddl-auto=update

 

If you recieve any further error after doing these steps, let us know in the comment box below.

0 0 vote
Article Rating
Subscribe
Notify of
guest
10 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Paul
Paul
1 year ago

hello sir,
my name is Paul from India ,
your video classes are very helpful to us to learn our own , we are expecting more from you in real time work on companies.

my request is can provide logic or code for edit form and Update form with respect to JSP, because some of companies still using JSP for display logic.

Thanking you sir …

Oualid Berrim
Oualid Berrim
10 months ago

Hello,
I hope that my message finds you well.
I am having an issue with the “findById” method . I am using Inteliie and It can not recognize the “Optional” keyword

ifiok ukpong
ifiok ukpong
7 months ago

Hello Kindson after adding the spring.jpa.hibernate.ddl-auto=update and others i still have errors, have tried googling it to find a solution but havent seen a result yet…hope u get this msg asap

Bartholomeus
Bartholomeus
5 months ago

Hello Sir.. Thanks for your tutorial & video.. it was helpful for me.. currently i am still beginner on spring boot..

i want to ask.. on point 9, why it has to declare default constructor ?

okash
okash
3 months ago

good evening sir really like your tutorial it was really helpful but i have run time error

Caused by: java.lang.IllegalStateException: Unable to set value for property driver-class-name

Caused by: java.lang.RuntimeException: Failed to load driver class org.h2.Driver in either of HikariConfig class loader or Thread context classloader

Caused by: java.lang.reflect.InvocationTargetException: null
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_162]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_162]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_162]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_162]

okash
okash
3 months ago

i am using intelj compiler

Sasi
Sasi
1 month ago

***************************
APPLICATION FAILED TO START
***************************

Description:

Field studentRepository in student.StudentService required a bean of type ‘student.StudentRepository’ that could not be found.

The injection point has the following annotations:
– @org.springframework.beans.factory.annotation.Autowired(required=true)

Action:

Consider defining a bean of type ‘student.StudentRepository’ in your configuration.

laxman
laxman
1 month ago
Reply to  Sasi

same error