This tutorial is part of Springing into Action: A Spring Boot Journey from Novice to Pro Series, be sure to check it out for more related content!
In this tutorial, we will learn how to create a simple application using Spring Boot and JPA Repository, including pagination. We will use a MySQL database to persist our data and will create a REST API to perform CRUD operations on it.
Prerequisites
Java 8 or later
Maven 3.x
MySQL Server
Spring Boot CLI
An IDE like Eclipse or IntelliJ IDEA
Setting up the Project
First, we need to create a new Spring Boot project using the Spring Initializer. We will select the following dependencies:
Spring Web
Spring Data JPA
MySQL Driver
Once the project is generated, we can import it into our IDE and start adding our code.
Configuring the Database
Next, we will configure our MySQL database by adding the following properties to our application.properties
file:
spring.datasource.url=jdbc:mysql://<host>:<port>/<dbname>
spring.datasource.username=<username>
spring.datasource.password=<password>
Make sure to replace the placeholders with the appropriate values for your MySQL server.
Creating the Entity
We will create two entities, Student
and Course
, to represent our data. The Student
entity will have a one-to-many relationship with the Course
entity.
@Entity
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@OneToMany(mappedBy = "student", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private List<Course> courses;
// getters and setters
}
@Entity
public class Course {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@ManyToOne
@JoinColumn(name = "student_id")
private Student student;
// getters and setters
}
Creating the Repository
We will create a JPA repository for each entity to perform CRUD operations on our data.
public interface StudentRepository extends JpaRepository<Student, Long> {
}
public interface CourseRepository extends JpaRepository<Course, Long> {
}
Creating the REST API
We will create a REST controller for each entity to handle the HTTP requests.
@RestController
@RequestMapping("/students")
public class StudentController {
@Autowired
private StudentRepository studentRepository;
@Autowired
private CourseRepository courseRepository;
@GetMapping
public Page<Student> getAllStudents(Pageable pageable) {
return studentRepository.findAll(pageable);
}
@PostMapping
public Student addStudent(@RequestBody Student student) {
return studentRepository.save(student);
}
@PutMapping("/{studentId}")
public Student updateStudent(@PathVariable Long studentId, @RequestBodyStudent student) {
student.setId(studentId); return studentRepository.save(student); }
@DeleteMapping("/{studentId}")
public void deleteStudent(@PathVariable Long studentId) {
studentRepository.deleteById(studentId);
}
@GetMapping("/{studentId}/courses")
public List<Course> getStudentCourses(@PathVariable Long studentId) {
return courseRepository.findByStudentId(studentId);
}
}
@RestController
@RequestMapping("/courses")
public class CourseController {
@Autowired
private CourseRepository courseRepository;
@GetMapping
public Page<Course> getAllCourses(Pageable pageable) {
return courseRepository.findAll(pageable);
}
@PostMapping
public Course addCourse(@RequestBody Course course) {
return courseRepository.save(course);
}
@PutMapping("/{courseId}")
public Course updateCourse(@PathVariable Long courseId, @RequestBody Course course) {
course.setId(courseId);
return courseRepository.save(course);
}
@DeleteMapping("/{courseId}")
public void deleteCourse(@PathVariable Long courseId) {
courseRepository.deleteById(courseId);
}
}
In the above code examples, we have added pagination by passing a Pageable
object to our repository's findAll()
method. This allows us to retrieve a specific page of data from our database.
Running the Application
Once the project is set up, we can run it using the following command:
mvn spring-boot:run
We can now test our REST API by sending HTTP requests to the appropriate endpoints.
In this tutorial, we have learned how to create a simple application using Spring Boot and JPA Repository, including pagination. We have also seen how easy it is to perform CRUD operations on a MySQL database using this framework.
I hope you found this tutorial helpful, and that you can use this as a starting point for your next project.
Note: above code is a simplified version for demonstration purposes, it's not ready to use code, you may need to customize it according to your requirement.