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.