View video tutorial

SPRING BOOT MySQL

SPRING BOOT

Spring Boot, MySQL, and Spring Data JPA help you build data-driven RESTful applications using minimal configuration and object relational mapping (ORM), where boilerplate code is completely eliminated.

Spring Boot in data access.


➔ Spring Boot provides a production-ready environment for application development, so that developers can focus directly on business logic development instead of worrying about application configuration and setup.

➔ Spring Boot eliminates boilerplate configuration code and tedious setup and creates a production-ready application in a very short time.

➔ Spring Boot is based on the Spring Framework, and therefore it inherently contains all the features of Spring.

➔ Spring Boot has become very popular among developers these days due to its fast application development speed.

Spring Boot with MySQL Database.


➔ MySQL is a very popular and lightweight RDBMS (Relational Database Management System). It is an open source and free software developed and maintained by Oracle.

➔ The MySQL database is ideal for organizations of all sizes, from small to large, because it is reliable, extremely fast at processing data and responding to queries, and easy to use.

➔ Supported and compatible with standard SQL (Structured Query Language).

➔ MySQL supports the Workbench tool, which is a user-friendly graphical user interface tool that allows you to easily manage databases, tables, columns, and data types.

Spring Boot and Spring Data JPA.


Spring boot can connect to and work with any database, so Spring boot can naturally work seamlessly with popular databases like MySQL. Database connectivity can be achieved through any of several common methods, such as:

➔ Using Spring Data JPA

➔ Using JPA (Java Persistence API)

➔ Using Hibernate Object Relational Mapping (ORM)

➔ Using simple JDBC (Java Database Connectivity)

Now practice this chapter in your learning environment.

Creating a Spring Boot project using the popular IDE IntelliJ IDEA..

Step 01: Create a Spring Boot Project. File -> New -> Project

Create a spring boot project

Step 02: Spring Boot Project setup

Spring Boot Project setup

Step 03: Spring Boot Project dependency

Spring Boot DevTools, Spring Web, Spring Data JPA, MySQL Driver

Spring Boot Project dependency

Project dependencies pom.xml file:


➔ pom.xml (Project Object Model) is the main configuration file for Maven-based Spring Boot applications, which defines project metadata, manages project dependencies, and configures the build process.

➔ The pom.xml file must be in the root directory of your project and is an ideal location for Maven-based applications.

code
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>4.0.5</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.exam</groupId>
    <artifactId>sbspringdatamysql</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>sbspringdatamysql</name>
    <description>sbspringdatamysql</description>
    <url/>
    <licenses>
        <license/>
    </licenses>
    <developers>
        <developer/>
    </developers>
    <scm>
        <connection/>
        <developerConnection/>
        <tag/>
        <url/>
    </scm>
    <properties>
        <java.version>17</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-webmvc</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>com.mysql</groupId>
            <artifactId>mysql-connector-j</artifactId>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-validation</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-webmvc-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

Step 04: Add dependency for spring-boot-starter-validation manually in pom.xml

spring boot spring-boot-starter-validation

Organize code into packages:


➔ The project code can be organized into packages according to function, such as the models, repositories, services, controllers listed below, and some classes and interfaces can be created inside these packages.

➔ Using packages to organize coding files in a project is a good programming practice.

04 Spring Boot Project structure (create packages)

Spring Boot Project structure

Spring Boot application.properties file:


➔ To establish a database connection and perform data access operations, a Spring Boot application needs to configure MySQL database properties and Hibernate properties through its application.properties file.

➔ Most of the entries in the application.properties file are self-explanatory.

Step 05: Spring Boot application.properties

code
spring.application.name=sbspringdatamysql
# If the project cannot be run due to port conflicts, change the server port.
server.port=8090
# Spring DATASOURCE DataSourceProperties
spring.datasource.url = jdbc:mysql://localhost:3306/demodb
spring.datasource.username = root
spring.datasource.password = mysql123
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

# Hibernate Properties
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQLDialect
# Hibernate ddl-auto (create, create-drop, validate, update)
spring.jpa.hibernate.ddl-auto = update

Entity or Model class:


➔ In Spring Boot, the terms 'Model' and 'Entity' are often used to describe data-holding classes, but their function can be described slightly differently.

Entity: An Entity is a Java class that is directly mapped to a database table, and the main function of the Spring Data JPA layer is to represent the data in the database table.

Model: Model is a broad term for classes that represent data for business logic or user interfaces, and these classes are used to exchange data between the frontend or backend, or both.

Step 06: Entity class User.java

code
package com.exam.sbspringdatamysql.entity;

import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;

@Entity
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long userId;
    private String name;
    private String email;

    public User() {
    }

    public User(Long userId) {
        this.userId = userId;
    }

    public User(Long userId, String name, String email) {
        this.userId = userId;
        this.name = name;
        this.email = email;
    }

    public Long getUserId() {
        return userId;
    }

    public void setUserId(Long userId) {
        this.userId = userId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    @Override
    public String toString() {
        return "User{" +
                "userId=" + userId +
                ", name='" + name + '\'' +
                ", email='" + email + '\'' +
                '}';
    }
}

JpaRepository


➔ JpaRepository is a Java Persistence API (JPA) interface that extends the CrudRepository and PagingAndSortingRepository interfaces.

➔ So, JpaRepository has full API support for basic CRUD operations as well as API support for pagination and sorting.

➔ In addition to the basic predefined standard queries, it is also possible to implement custom queries using the query method naming convention or the @Query annotation.

Step 07: Repository interface UserRepository.java

code
package com.exam.sbspringdatamysql.repository;

import com.exam.sbspringdatamysql.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface UserRepository extends JpaRepository<User,Long> {
}

Service Layer


➔ Process business logic and core application rules.

➔ Works with domain models, DTOs, Entities, and Java objects.

➔ Calls the repository layer to process data.

Step 08: Service class UserService.java

code
package com.exam.sbspringdatamysql.service;

import com.exam.sbspringdatamysql.entity.User;
import com.exam.sbspringdatamysql.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

@Service
public class UserService {
    @Autowired
    private UserRepository repository;

    public List<User> fetchUsers() {
        return repository.findAll();
    }

    public Optional<User> fetchUsersById(Long id) {
        return repository.findById(id);
    }

    public User insertUser(User user) {
        return repository.save(user);
    }

    public User editUser(User user) {
        return repository.save(user);
    }

    public String removeUser(Long id) {
        repository.deleteById(id);
        return "Deleted Successfully";
    }
}

Controller Layer


➔ Handles HTTP requests and communicates with the presentation layer.

➔ Works with HTTP Requests, RequestParam, PathVariable, and JSON.

➔ The controller calls the service layer to process the data.

Step 09: Controller class UserController.java

code
package com.exam.sbspringdatamysql.controller;

import com.exam.sbspringdatamysql.entity.User;
import com.exam.sbspringdatamysql.service.UserService;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

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

@RestController
@RequestMapping("api")
public class UserController {
    @Autowired
    private UserService service;

    // Insert operation
    @PostMapping("/user")
    public User insertUser(@Valid @RequestBody User user)
    {
        return service.insertUser(user);
    }
    //Fetch operation
    @GetMapping("/user")
    public List<User> fetchUsers()
    {
        return service.fetchUsers();
    }
    //Fetch operation
    @GetMapping("/user/{id}")
    public User fetchUsersById(@PathVariable Long id)
    {
        Optional<User> user = service.fetchUsersById(id);
         if(user.isPresent()){
             return  user.get();
         }
        return null;
    }

    //Edit operation
    @PutMapping("user/{id}")
    public User editUser(@PathVariable Long id, @RequestBody User frontendUser) {
        Optional<User> user = service.fetchUsersById(id);
        if (user.isPresent()) {
            User backendUser = user.get();
            backendUser.setName(frontendUser.getName());
            backendUser.setEmail(frontendUser.getEmail());
            return service.editUser(backendUser);
        }
        return null;
    }

    //Remove operation
    @DeleteMapping("user/{id}")
    public String removeUser(@PathVariable Long id) {
         return service.removeUser(id);
    }
}

Step 10: Run Project by Right click on SbspringdatamysqlApplication.java class annotated with @SpringBootApplication

spring boot application run

Now test CRUD operation in Postman (an API testing tool).

Step 11: Save data to MySQL using Spring Data JPA

postmapping json

Step 12: Get all data from MySQL using Spring Data JPA

getmapping all json data

Step 13: Get data retrieved by id from MySQL using Spring Data JPA

getmapping json data by id

Step 14: Update data by id to MySQL using Spring Data JPA

update data by id

Step 15: Delete data by id from MySQL using Spring Data JPA

delete data by id

Step 16: Check data in MySQL using Workbench

Check data in MySQL using Workbench

Download source code .zip file, of this project.