Create REST API using Spring Boot, Hibernate and MySQL

Piyumi Sudusinghe
6 min readSep 27, 2023

--

Hello Everyone! 😃

This is the fifth article of my Spring Boot series. In the first four articles, we have created a Spring Boot application and connected a database with the application. Let’s create a REST API using that knowledge👏.

If you are interested in previous articles you can start from here. ➡️

Prerequisite: Need to implement the initial project structure referring to the first four articles. ( Spring boot application which connects with a MySQL database).

If you want to get a detailed idea about the architecture of the project you can refer to the below article.

This REST API allows the following functional requirements.
1. Retrieve the details of Students.

2. Create a new student.

3. Update student details.

4. Delete a student.

Get details of all students

Create a repository class for Students to retrieve details from the database.

package com.springboot.mysql.modal;

import jakarta.persistence.*;

import java.util.Date;

@Entity
@Table
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String firstName;
private String lastName;
private Date birthday;
private String department;

public Long getId() {
return id;
}

public void setId(Long id) {
this.id = id;
}

public String getFirstName() {
return firstName;
}

public void setFirstName(String firstName) {
this.firstName = firstName;
}

public String getLastName() {
return lastName;
}

public void setLastName(String lastName) {
this.lastName = lastName;
}

public Date getBirthday() {
return birthday;
}

public void setBirthday(Date birthday) {
this.birthday = birthday;
}

public String getDepartment() {
return department;
}

public void setDepartment(String department) {
this.department = department;
}
}

Here we extend the methods in the JPA repository class which contains all the CRUD operations.

Then create a service class to access the method in the repository as follows.

package com.springboot.mysql.service;

import com.springboot.mysql.modal.Student;
import com.springboot.mysql.repository.StudentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class StudentService {
@Autowired
StudentRepository studentRepository;

public List<Student> getAllStudents()
{
return studentRepository.findAll();
}
}

Then we need a controller class to add the get method to retrieve student details.

package com.springboot.mysql.controller;

import com.springboot.mysql.modal.Student;
import com.springboot.mysql.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class StudentController {
@Autowired
StudentService studentService;

@GetMapping("/students")
public List<Student> getAllStudents()
{
return studentService.getAllStudents();
}
}

After these changes, we can up the spring boot application. We can use Postman to test the get endpoint.

Get details of one student

We need to add a new method to the controller class to retrieve the details of one student. We need to specify the ID of the student in order to get the details of the student and the ID should be sent with the URL (/students/{id})

import java.util.List;

@RestController
public class StudentController {
@Autowired
StudentService studentService;

@GetMapping("/students")
public List<Student> getAllStudents()
{
return studentService.getAllStudents();
}

@GetMapping("/students/{id}")
public Student getStudent(@PathVariable Long id)
{
return studentService.getStudent(id);
}
}

Add another method in the service class to retrieve student details from the repository.

package com.springboot.mysql.service;

import com.springboot.mysql.modal.Student;
import com.springboot.mysql.repository.StudentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class StudentService {
@Autowired
StudentRepository studentRepository;

public List<Student> getAllStudents()
{
return studentRepository.findAll();
}

public Student getStudent(Long id)
{
Optional<Student> student = studentRepository.findById(id);
return student.orElse(null);
}
}

Using Postman you can test this endpoint also as follows.

Add new student

We need to add a new method in the controller class to create a new student. Details of the new student are in the request body.

package com.springboot.mysql.controller;

import com.springboot.mysql.modal.Student;
import com.springboot.mysql.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class StudentController {
@Autowired
StudentService studentService;

@GetMapping("/students")
public List<Student> getAllStudents()
{
return studentService.getAllStudents();
}

@GetMapping("/students/{id}")
public Student getStudent(@PathVariable Long id)
{
return studentService.getStudent(id);
}

@PostMapping("/student/")
public Student createStudent(@RequestBody Student student )
{
return studentService.createStudent(student);
}
}

Add another method in the service class to create a new student via the repository.

package com.springboot.mysql.service;

import com.springboot.mysql.modal.Student;
import com.springboot.mysql.repository.StudentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class StudentService {
@Autowired
StudentRepository studentRepository;

public List<Student> getAllStudents()
{
return studentRepository.findAll();
}

public Student getStudent(Long id)
{
Optional<Student> student = studentRepository.findById(id);
return student.orElse(null);
}

public Student createStudent(Student student)
{
studentRepository.save(student);
return studentRepository.findById(student.getId()).orElse(null);
}
}

Using Postman you can test this endpoint also as follows.

You can retrieve the student details and verify whether student details are saved in the database or not.

And we can check the database by using a select query.

Delete a student from the database

We need to add a new method to the controller class to delete the details of a student. We need to specify the ID of the student in order to delete the details of the student and the ID should be sent with the URL (/students/{id}).

package com.springboot.mysql.controller;

import com.springboot.mysql.modal.Student;
import com.springboot.mysql.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class StudentController {
@Autowired
StudentService studentService;

@GetMapping("/students")
public List<Student> getAllStudents()
{
return studentService.getAllStudents();
}

@GetMapping("/students/{id}")
public Student getStudent(@PathVariable Long id)
{
return studentService.getStudent(id);
}

@PostMapping("/student/")
public Student createStudent(@RequestBody Student student )
{
return studentService.createStudent(student);
}

@DeleteMapping("/students/{id}")
public String removeStudent(@PathVariable Long id)
{
return studentService.removeStudent(id);
}
}

Add another method in the service class to delete the student via the repository.

package com.springboot.mysql.service;

import com.springboot.mysql.modal.Student;
import com.springboot.mysql.repository.StudentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class StudentService {
@Autowired
StudentRepository studentRepository;

public List<Student> getAllStudents()
{
return studentRepository.findAll();
}

public Student getStudent(Long id)
{
Optional<Student> student = studentRepository.findById(id);
return student.orElse(null);
}

public Student createStudent(Student student)
{
studentRepository.save(student);
return studentRepository.findById(student.getId()).orElse(null);
}

public String removeStudent(Long id)
{
studentRepository.deleteById(id);
return "Successfully removed the student with id : " + id;
}
}

Using Postman, we can check this endpoint.

Since the student with ID 4 is deleted from the database, we receive an empty result for the get request.

The source code for this project is available here — https://github.com/piyumisudusinghe/SpringBoot_RestAPI

Let’s improve our REST API by handling errors in the API. 🔽

--

--