Introduction
In this section of the chapters, we will build CRUD REST APIs for a Student Management System Project with a MySQL database. We will create and set up a Spring Boot project in IntelliJ IDEA, using a three-layer architecture. We will configure the MySQL database, create a Student JPA entity, and a repository to interact with the database. Each step will be explained in detail to help you understand the process. In the next chapter, we will learn how to build a save Student REST API with a MySQL database.
What We Will Cover in This Chapter
- Create and Setup Spring Boot Project in IntelliJ IDEA
- Using Three Layer Architecture (Controller -> Service -> Repository) – explained in detail
- Configure MySQL Database
- Create Student JPA Entity
- Create Student Repository
- Add explanations to each step
- Note on Hibernate dialect being optional in the latest version
Create and Setup Spring Boot Project in IntelliJ IDEA
Create a New Spring Boot Project
- Open IntelliJ IDEA:
- Launch IntelliJ IDEA from your installed applications.
- Start a New Project:
- On the welcome screen, click “New Project”.
- Select Project Type:
- Choose “Spring Initializr” from the project type options.
- Configure Project Metadata:
- Group:
com.example - Artifact:
springboot-mysql-crud - Name:
springboot-mysql-crud - Description:
Spring Boot CRUD Operations with MySQL - Package name:
com.example.springbootmysqlcrud - Packaging:
Jar - Java Version:
17(or the latest version available)
- Group:
- Select Dependencies:
- Add the following dependencies:
- Spring Web
- Spring Data JPA
- MySQL Driver
- Add the following dependencies:
- Generate and Import Project:
- Click “Generate” to download the project as a ZIP file.
- Extract the ZIP file and open the project in IntelliJ IDEA.
Explanation
- Spring Initializr: A web-based tool provided by Spring to bootstrap a new Spring Boot project with dependencies and configurations.
- Group and Artifact: Define the project’s Maven coordinates.
- Dependencies: Adding dependencies ensures that the necessary libraries are included in the project for web development, JPA, and MySQL connectivity.
Using Three-Layer Architecture
We will follow a three-layer architecture: Controller -> Service -> Repository.
Explanation
- Controller: Handles HTTP requests and responses. It acts as an entry point for the client to interact with the application.
- Service: Contains business logic and interacts with the repository. It processes the input from the controller, applies business rules, and calls the repository layer for data access.
- Repository: Interacts with the database to perform CRUD operations. It abstracts the data access layer and provides an interface to perform database operations.
Configure MySQL Database
Update application.properties
- Open
application.properties:- Navigate to
src/main/resources/application.properties.
- Navigate to
- Add MySQL Configuration:
- Add the following properties to configure the MySQL database connection:
spring.datasource.url=jdbc:mysql://localhost:3306/your_database_name
spring.datasource.username=your_mysql_username
spring.datasource.password=your_mysql_password
spring.jpa.hibernate.ddl-auto=update
Explanation
spring.datasource.url: The JDBC URL to connect to the MySQL database. Replaceyour_database_namewith the actual name of your database.spring.datasource.username: The username to connect to the MySQL database. Replaceyour_mysql_usernamewith your MySQL username.spring.datasource.password: The password to connect to the MySQL database. Replaceyour_mysql_passwordwith your MySQL password.spring.jpa.hibernate.ddl-auto: Specifies the Hibernate DDL mode. Setting it toupdateautomatically updates the database schema based on the entity mappings.
Note on Hibernate Dialect
In the latest versions of Spring Boot, specifying the Hibernate dialect is optional because Spring Boot can automatically detect the database type and configure the appropriate dialect. However, you can still specify the dialect explicitly if needed:
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect
Create Student JPA Entity
Create the Student Class
- Create a New Package:
- In the
src/main/java/com/example/springbootmysqlcruddirectory, create a new package namedmodel.
- In the
- Create the
StudentClass:- Inside the
modelpackage, create a new class namedStudent. - Add the following code to the
Studentclass:
- Inside the
package com.example.springbootmysqlcrud.model;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
@Entity
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String firstName;
private String lastName;
private String email;
// Constructors
public Student() {}
public Student(String firstName, String lastName, String email) {
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
}
// Getters and Setters
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 String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
Explanation
@Entity: Specifies that the class is an entity and is mapped to a database table.@Id: Specifies the primary key of the entity.@GeneratedValue: Specifies how the primary key should be generated.GenerationType.IDENTITYindicates that the primary key is auto-incremented.
Create Student Repository
Create the StudentRepository Interface
- Create a New Package:
- In the
src/main/java/com/example/springbootmysqlcruddirectory, create a new package namedrepository.
- In the
- Create the
StudentRepositoryInterface:- Inside the
repositorypackage, create a new interface namedStudentRepository. - Add the following code to the
StudentRepositoryinterface:
- Inside the
package com.example.springbootmysqlcrud.repository;
import com.example.springbootmysqlcrud.model.Student;
import org.springframework.data.jpa.repository.JpaRepository;
public interface StudentRepository extends JpaRepository<Student, Long> {
}
Explanation
JpaRepository: TheStudentRepositoryinterface extendsJpaRepository, providing CRUD operations for theStudententity. TheJpaRepositoryinterface includes methods likesave(),findById(),findAll(),deleteById(), etc.- Generics: The
JpaRepositoryinterface takes two parameters: the entity type (Student) and the type of its primary key (Long).
Conclusion
In this chapter, we set up a Spring Boot project in IntelliJ IDEA, configured it to use a MySQL database, and created a Student JPA entity and repository. Each step was explained in detail to help you understand the process. In the next chapter, we will learn how to build a save Student REST API with a MySQL database.