Spring Boot MySQL CRUD Operations: Setup the Spring Boot Project

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

  1. Open IntelliJ IDEA:
    • Launch IntelliJ IDEA from your installed applications.
  2. Start a New Project:
    • On the welcome screen, click “New Project”.
  3. Select Project Type:
    • Choose “Spring Initializr” from the project type options.
  4. 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)
  5. Select Dependencies:
    • Add the following dependencies:
      • Spring Web
      • Spring Data JPA
      • MySQL Driver
  6. 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

  1. Open application.properties:
    • Navigate to src/main/resources/application.properties.
  2. 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. Replace your_database_name with the actual name of your database.
  • spring.datasource.username: The username to connect to the MySQL database. Replace your_mysql_username with your MySQL username.
  • spring.datasource.password: The password to connect to the MySQL database. Replace your_mysql_password with your MySQL password.
  • spring.jpa.hibernate.ddl-auto: Specifies the Hibernate DDL mode. Setting it to update automatically 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

  1. Create a New Package:
    • In the src/main/java/com/example/springbootmysqlcrud directory, create a new package named model.
  2. Create the Student Class:
    • Inside the model package, create a new class named Student.
    • Add the following code to the Student class:
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.IDENTITY indicates that the primary key is auto-incremented.

Create Student Repository

Create the StudentRepository Interface

  1. Create a New Package:
    • In the src/main/java/com/example/springbootmysqlcrud directory, create a new package named repository.
  2. Create the StudentRepository Interface:
    • Inside the repository package, create a new interface named StudentRepository.
    • Add the following code to the StudentRepository interface:
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: The StudentRepository interface extends JpaRepository, providing CRUD operations for the Student entity. The JpaRepository interface includes methods like save(), findById(), findAll(), deleteById(), etc.
  • Generics: The JpaRepository interface 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.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top