Spring Boot + MySQL Database example (CRUD) in Java

Spring Boot + MySQL Database example (CRUD) in Java

Java

Spring Boot + MySQL Database example (CRUD) in Java


Introducing Spring Boot and Spring Framework:

  1. The Power of Spring Framework: The Spring framework is a popular Java framework known for its extensive features and capabilities in building enterprise-grade applications. It provides a robust set of tools and functionalities, including dependency injection, aspect-oriented programming, data access, and more. Spring Framework promotes modular and maintainable code, making it a top choice for developers.

  2. Streamlined Development with Spring Boot: Spring Boot takes the Spring framework to the next level by significantly reducing the configuration and setup time required for Spring projects. With Spring Boot, you can start a project with minimal settings and quickly focus on developing the essential features specific to your application. It simplifies the development process and allows for rapid prototyping and deployment.

Introducing the Purpose of the Blog:

In this Spring Boot tutorial, we will guide you through the development of RESTful web service APIs for performing CRUD (Create, Retrieve, Update, Delete) operations on a MySQL database. This comprehensive tutorial will equip you with the necessary knowledge and practical skills to build robust APIs using Spring Boot.

 
 
Spring Boot + MySQL database example (CRUD)
 
 
 

1. Create the Project

We will explore different methods to create a Spring project, with a particular focus on using the Spring Initializer tool. By visiting http://start.spring.io/ and following the provided steps, you will be able to generate a new project with ease. We will also provide the necessary details, such as group, artifact, package, and dependencies, for our example project.
 
Enter the following details to create our example project.
 
        Group : com.example
        Artifact: studentproject
        Pacakge : com.example.studentproject
        Dependecies : WebJPAMySQL, DevTools

The dependencies will be added to our pom.xml file and if you want, you can add more dependencies or reduce them manually later on.
 
how to create project with Spring Boot + MySQL database
 



Once all the details are entered, click to GENERATE to create and download your customized initial project. Spring Initializer will generate the project with the details you have entered and download a zip file with all the project folders.



The below picture is showing the structure of the project.

 
Spring Boot + MySQL Project Structure


 
Let's have a look into important directories inside the project.
 

2. The main entry point of the application.

The "StudentprojectApplication" class serves as the main entry point for our Spring Boot application. We will discuss its significance and how it contributes to the overall project structure.
 
package com.example.studentproject;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class StudentprojectApplication {

public static void main(String[] args) {
SpringApplication.run(StudentprojectApplication.class, args);
}

}
This contains the @SpringBootApplication annotation which is a combination of the following specific annotations.
 
@Configuration - Spring bootstraps any class annotated with the @Configuration annotation and uses it as a source for other bean definitions.
 
@ComponentScan - It instructs Spring to look for and bootstrap any other components in the current package.
 
@EnableAutoConfiguration - This annotation instructs Spring to configure your application automatically depending on the dependencies you specified in the pom.xml file.
 

3. Resources folder 

The resources folder holds various static resources, templates, and property files required for the application. We will delve into the purpose of this folder and its subdirectories, including the "static" and "templates" folders. Additionally, we will explore the "application.properties" file, which stores application-wide properties and configurations, such as server port, context path, and database URL.
 
This folder may have the following subfolders depending on your project.
 
  1. resources/ static
  
  2. resources/templates 
 
 3. resources/application.properties - This is used to store the application-wide properties of your application and helps wot read those properties to configure your application. This file can have the server's default port, server's context path, database URL, etc.
 
4. Configure MYSQL database
To establish a connection with a MySQL database, we will leverage the "application.properties" file mentioned earlier. You will learn how to configure the database connection by updating the URL, username, and password according to your specific MySQL database server.
 
server.port=8080

spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://localhost/starbucks?createDatabaseIfNotExist=true
spring.datasource.username=root
spring.datasource.password=
spring.jpa.database-platform=org.hibernate.dialect.MySQL5InnoDBDialect
Here, you need to update the URL username and password according to your MySQL database server.

5. Code Domain Model Class

We will create the "Student" class, which maps to the product table in the database. This domain model class represents the data structure and properties of our entities.
 
package com.student.crudapp.model;
import com.student.crudapp.repository.StudentRepository;
import org.springframework.beans.factory.annotation.Autowired;

import javax.persistence.*;

@Entity
public class Student {

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int id;

private String name;

private String email;

private String grade;

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

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;
}

public String getGrade() {
return grade;
}

public void setGrade(String grade) {
this.grade = grade;
}

@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
", email='" + email + '\'' +
", grade='" + grade + '\'' +
'}';
}
}
This is a simple domain model class, with class names and field names are identical to table names and column names in the database. This allows you to have a minimum number of JPA annotations.
 

6. Code Repository Class

The repository class serves as the interface between the application and the database. We will create the "StudentRepository" class, responsible for executing database operations and queries related to the "Student" entity.
package com.student.crudapp.repository;
import com.student.crudapp.model.Student;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;

public interface StudentRepository extends JpaRepository<Student, Integer> {
List<Student> findAll();
Student findById(int id);
int deleteById(int id);

}
The spring data JPA will generate implementation code for the most common CRUD operations and you do not need to stick with customized queries. This is one advantage that you will get from using the spring data JPA.
 

7, Code Service Class

The service class acts as a middle layer between the persistence layer (repository) and the controller layer. We will create the "StudentService" class, which handles business logic and orchestrates data retrieval and manipulation.
 

package service;

import com.student.crudapp.model.Student;
import com.student.crudapp.repository.StudentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.List;

@Service
@Transactional
public class StudentService {

@Autowired
StudentRepository studentRepository;

//Get all the students
public List<Student> getAllStudents() {
List<Student> students = studentRepository.findAll();
return students;
}

//display one student by id
public Student getStudentById(int id) {
return studentRepository.findById(id);
}

//save student in database
public void saveStudent(Student student) {
try{
studentRepository.save(student);
}
catch(Exception e){
e.printStackTrace();
}
}

//delete stuednt by id
public void deleteStudent(int id) {
try{
studentRepository.deleteById(id);
}catch(Exception e){
e.printStackTrace();
}
}

}
All the methods are executed in transactions because this studentService class is marked with the @Transactional annotation.
 

8. Code REST Controller Class 

The REST controller class plays a crucial role in handling RESTful APIs for CRUD operations. We will provide the code for the "StudentController" class, which exposes the necessary endpoints for creating, retrieving, updating, and deleting student records.
package com.student.crudapp.controller;

import com.student.crudapp.model.Student;
import com.student.crudapp.repository.StudentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
public class StudentController {

@Autowired
StudentRepository studentRepository;

//check the api's working correctly api
@RequestMapping(value="/ping", method=RequestMethod.GET)
@ResponseBody
public String healthCheck() {
return "This is working well";
}


@RequestMapping(value="/students", method=RequestMethod.GET)
@ResponseBody
public List<Student> getAllStudents() {
return studentRepository.findAll();
}

@RequestMapping(value="/student", method=RequestMethod.POST)
@ResponseBody
public Student addStudent(Student student) {
return studentRepository.save(student);
}

@RequestMapping(value="/findstudent", method = RequestMethod.GET)
@ResponseBody
public Student findStudent(@RequestParam("studentId") int studentId) {
return studentRepository.findById(studentId);
}

@RequestMapping(value= "/updatestudent", method = RequestMethod.GET)
@ResponseBody
public Student updateStudent(@RequestBody Student student){
return studentRepository.save(student);
}

@RequestMapping(value="/deletestudent", method = RequestMethod.GET)
@ResponseBody
public int deleteStudent(@RequestParam("studentId") int studentId) {
return studentRepository.deleteById(studentId);
}
}
 
 
Here, the @Controller annotation is used to expose the RESTful APIs. The rest controller still takes advantage of the spring's dependency injection.

9. Code Spring Boot Application Class

To execute our application, we will utilize the built-in Spring Boot application class. This main class serves as the entry point for running the entire project, without the need for additional configuration or setup.
 
package com.student.crudapp;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class CrudappApplication {

public static void main(String[] args) {
SpringApplication.run(CrudappApplication.class, args);
}

}
 
 This class will start embedded Tomcat server hosting our Spring Boot web application.
The project will run on port 8080 and url http://localhost:8080/
Spring Boot + MySQL CRUD Example

10. Test the API and Project

Finally, we will examine the APIs in this project and demonstrate how to test them using the popular tool, Postman. 
This will allow you to validate and interact with the created APIs effectively..
1. Add a student (POST Request)
http://localhost:8080/student 
{ "name": "test", "email": "test@gmail.com", "grade": "05" }
2. Get all students (GET Request)
http://localhost:8080/students 
3. Find a student (GET Request)
http://localhost:8080/findstudent?studentId=1
 
4. Update a student (GET Request)
 
http://localhost:8090/updatestudent
{
    "name": "testupdated",
    "email": "testupdated@gmail.com",
    "grade": "05"
}
 
5. Delete a student (GET Request)
 
http://localhost:8090/deletestudent?studentId=1
 
This guide explains how to utilize the MySQL database in a Java application with Spring Boot. The tutorial focuses on creating a basic CRUD (Create, Read, Update, Delete) functionality using Spring Boot, MySQL, JPA, and Hibernate. As you delve deeper into Spring Boot, there are numerous additional concepts to explore. By following this tutorial, you will be able to construct a successful Restful CRUD API employing Spring Boot, MySQL, JPA, and Hibernate. We look forward to having you join us in the next tutorial. Until then, take care and goodbye!


Spring Boot + MySQL Database example (CRUD) in Java

How we spend our days is, of course, how we spend our lives.

May 24, 2023

0
0

Comments

Geoffrey Mesesi 1 year ago

This tutorial is a fantastic resource for anyone looking to learn and master Spring Boot for building RESTful APIs.

+

© 2024 Inc. All rights reserved. mulikevs