Creating a Simple Application with Spring Boot and JPA Repository

An experienced Software engineer with extensive knowledge in Fullstack development ( Java - Angular 8+ ) and Data Science.
Search for a command to run...

An experienced Software engineer with extensive knowledge in Fullstack development ( Java - Angular 8+ ) and Data Science.
No comments yet. Be the first to comment.
Learn to build web apps w/ Spring Boot, from setting up a project to advanced topics like REST APIs, databases & security. Detailed explanations, code examples & tips for all levels.
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! Dependency Injection (DI) is a fundamental concept in software development that allows objects to be de...
Docker: Use Cases and Why Docker is Important Introduction Docker has become an essential tool for modern software development and deployment. It enables developers to package their applications and dependencies into portable containers, making it ea...

Using Spring Boot with Apache Kafka: Building Event-Driven Systems Event-driven architectures are becoming increasingly popular as organizations move towards more distributed and decoupled systems. Apache Kafka is a popular open-source distributed st...
Building Reactive Systems with Spring Boot: Leveraging Spring WebFlux and Reactor In today's fast-paced world, where responsiveness and scalability are critical factors, building reactive systems has become a necessity. Reactive systems are those tha...
State Machine Diagrams in Spring Boot: Usage and Implementation State machine diagrams are a powerful tool for modeling complex behavior in software systems. In Spring Boot, the State Machine Framework provides an easy way to implement state machine ...
SOLID Principles in Spring Boot: A Comprehensive Guide SOLID is an acronym for the 5 principles of object-oriented design that promote software maintainability, scalability, and readability. These principles were introduced by Robert C. Martin and ha...
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.
Java 8 or later
Maven 3.x
MySQL Server
Spring Boot CLI
An IDE like Eclipse or IntelliJ IDEA
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.
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.
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
}
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> {
}
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.
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.