0% found this document useful (0 votes)
27 views

CRUD Operations in Spring Boot and MySql (Rest APIs) - by Deep Patel - Medium - Imp

The document provides step-by-step instructions for creating REST APIs to perform CRUD operations on a MySQL database using Spring Boot. It explains how to set up the project structure, create entities, repositories, services and controllers to enable creating, retrieving, updating and deleting database records.

Uploaded by

Akanksha Ojha
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views

CRUD Operations in Spring Boot and MySql (Rest APIs) - by Deep Patel - Medium - Imp

The document provides step-by-step instructions for creating REST APIs to perform CRUD operations on a MySQL database using Spring Boot. It explains how to set up the project structure, create entities, repositories, services and controllers to enable creating, retrieving, updating and deleting database records.

Uploaded by

Akanksha Ojha
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

14/04/2024, 22:04 CRUD operations in Spring Boot and MySql (Rest APIs) | by Deep Patel | Medium

Get unlimited access to the best of Medium for less than $1/week. Become a member

CRUD operations in Spring Boot and MySql (Rest APIs)


Beginner-friendly step-by-step explanation to creating Restful APIs and perform Create, Retrieve, Update and Delete functionality
on MySql database with Spring framework.

Deep Patel · Follow


5 min read · Jan 1, 2023

Listen Share More

Hi all, today we will create a RESTful API in Spring Boot from scratch and perform CRUD operations on our MySql database.
Spring Boot is an open-source Java-based framework to build enterprise spring applications. The complete code link is available
at the end.

Spring Boot is a module of Spring Framework widely used to develop REST APIs. The primary feature of Spring Boot is
Autoconfiguration. It automatically configures the classes based on the requirement. Spring Boot offers embedded servers such
as Jetty and Tomcat, etc. Now, before moving to code, let's first look at its features and architecture.

Features of Spring Boot


Inversion of Control: Instead of the developer, the framework will take control to create the objects, configuring and
assembling their dependencies, and managing their entire life cycle.

Dependency Injection: Dependency Injection is a design pattern that removes the dependency of the programs and makes
them loosely coupled. Spring framework provides two ways to inject dependency: by Constructor, and by Setter method.

Spring Framework Architecture

https://deeppatel23.medium.com/crud-operations-in-spring-boot-and-mysql-rest-apis-9ca0c15bdc73 1/16
14/04/2024, 22:04 CRUD operations in Spring Boot and MySql (Rest APIs) | by Deep Patel | Medium

So, as per the architecture of spring boot, we will create different layers in our project. Different packages will be created for each
layer. We will go through the definitions of each layer as we implement them in our code.

Requirements
1. Maven 3.0+

2. IDE (Eclipse or IntelliJ)

3. JDK 1.8+

4. MySql database server

5. Postman or Insomnia for testing

1. Project Setup
Create project boilerplate and add dependencies from spring initializr

Select Maven project and Java language

Give a name to your project

Add dependencies for SpringWeb, MySql Driver and Spring Data JPA

Click on Generate

The project zip file will get downloaded, now unzip your folder

https://deeppatel23.medium.com/crud-operations-in-spring-boot-and-mysql-rest-apis-9ca0c15bdc73 2/16
14/04/2024, 22:04 CRUD operations in Spring Boot and MySql (Rest APIs) | by Deep Patel | Medium

2. Create the MySql database


Open MySql workbench or log in from terminal

Create new schema “emp”

CREATE SCHEMA `emp` ;

3. Configuring the database into your project


Open the unzipped file in your favourite IDE

Add database configuration to the application.properties file

https://deeppatel23.medium.com/crud-operations-in-spring-boot-and-mysql-rest-apis-9ca0c15bdc73 3/16
14/04/2024, 22:04 CRUD operations in Spring Boot and MySql (Rest APIs) | by Deep Patel | Medium

spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://localhost:3306/emp #change
spring.datasource.username=root #change
spring.datasource.password=12345678 #change
spring.datasource.driver-class-name =com.mysql.jdbc.Driver
spring.jpa.show-sql: true

4. Creating Employee Entity


Entities are persistence objects, where an entity represents a table in a relational database, and each entity instance corresponds
to a row in that table.

Create a new package, entity.

Add Java Class to entity package, named Employee and annotate with Entity annotation.

Add ID and other necessary fields to the Employee class

Right click -> Generate -> Getter and Setter -> select all variables; to generate getter setter methods

Similarly, generate all arguments constructer and no arguments constructer

https://deeppatel23.medium.com/crud-operations-in-spring-boot-and-mysql-rest-apis-9ca0c15bdc73 4/16
14/04/2024, 22:04 CRUD operations in Spring Boot and MySql (Rest APIs) | by Deep Patel | Medium

5. Creating a JPA repository


JPA stands for Java Persistence API (Application Programming Interface). JPA is a specification which specifies how to access,
manage and persist information/data between java objects and relational databases.

Create a new package, repository

Add Java Interface to repository package, named EmployeeRepository and annotate it with Repository annotation.

Extend your repository with the JPA repository

6. Creating a Service class


A service layer is a layer in an application that facilitates communication between the controller and the persistence/entity layer.
Additionally, business logic is stored in the service layer.

Create a new package, service

https://deeppatel23.medium.com/crud-operations-in-spring-boot-and-mysql-rest-apis-9ca0c15bdc73 5/16
14/04/2024, 22:04 CRUD operations in Spring Boot and MySql (Rest APIs) | by Deep Patel | Medium
Add Java Interface to service package, named EmployeeService

Add the definitions of the following functions to it

public interface EmployeeService {

Employee saveEmployee(Employee employee);

List<Employee> fetchAllEmployees();

Employee getEmployeeById(Long id);

Employee updateEmployeeById(Long id, Employee employee);

String deleteDepartmentById(Long id);


}

Then in the same package, create Java Class, EmployeeServiceImpl implementing EmployeeService. This class will be
annotated with @ Service annotation.

Add an object for EmployeeRepository and Autowire it. Autowire is used to inject dependency. This annotation will directly
call the necessary getter/setter and other methods when needed.

package com.example.crud.service;

import com.example.crud.entity.Employee;
import com.example.crud.repository.EmployeeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

@Service
public class EmployeeServiceImpl implements EmployeeService{

@Autowired
private EmployeeRepository employeeRepository;

@Override
public Employee saveEmployee(Employee employee) {
return employeeRepository.save(employee);
}

@Override
public List<Employee> fetchAllEmployees() {
List<Employee> allEmployees = employeeRepository.findAll();
return allEmployees;
}

@Override Open in app


public Employee getEmployeeById(Long id) {
Optional<Employee> employee = employeeRepository.findById(id);
ifSearch
(employee.isPresent()) {
return employee.get();
}
return null;
}

@Override
public Employee updateEmployeeById(Long id, Employee employee) {
Optional<Employee> employee1 = employeeRepository.findById(id);

if (employee1.isPresent()) {
Employee originalEmployee = employee1.get();

if (Objects.nonNull(employee.getEmployeeName()) && !"".equalsIgnoreCase(employee.getEmployeeName())) {


originalEmployee.setEmployeeName(employee.getEmployeeName());
}
if (Objects.nonNull(employee.getEmployeeSalary()) && employee.getEmployeeSalary() != 0) {

https://deeppatel23.medium.com/crud-operations-in-spring-boot-and-mysql-rest-apis-9ca0c15bdc73 6/16
14/04/2024, 22:04 CRUD operations in Spring Boot and MySql (Rest APIs) | by Deep Patel | Medium
originalEmployee.setEmployeeSalary(employee.getEmployeeSalary());
}
return employeeRepository.save(originalEmployee);
}
return null;
}

@Override
public String deleteDepartmentById(Long id) {
if (employeeRepository.findById(id).isPresent()) {
employeeRepository.deleteById(id);
return "Employee deleted successfully";
}
return "No such employee in the database";
}
}

7. Creating the controller


The controller method starts to process the web request by interacting with the service layer to complete the work that needs to
be done. RestController helps us in creating rest-based web services.

Create a new package, controller

Add Java Class to controller package, named EmployeeController

Here, we will all our Rest APIs and call necessary functions.

Add the following code:

package com.example.crud.controller;

import com.example.crud.entity.Employee;
import com.example.crud.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class EmployeeController {

@Autowired
private EmployeeService employeeService;

@PostMapping("/employee")
public Employee saveEmployee(@RequestBody Employee employee) {
return employeeService.saveEmployee(employee);
}

@GetMapping("/employee")
public List<Employee> getAllEmployees() {
return employeeService.fetchAllEmployees();
}

@GetMapping("/employee/{id}")
public Employee getEmployeeById(@PathVariable("id") Long id) {
return employeeService.getEmployeeById(id);
}

@PutMapping("/employee/{id}")
public Employee updateEmployee(@PathVariable("id") Long id, @RequestBody Employee employee) {
return employeeService.updateEmployeeById(id, employee);
}

@DeleteMapping("/employee/{id}")
public String deleteEmployee(@PathVariable("id") Long id) {
return employeeService.deleteDepartmentById(id);
}
}

8. Testing the APIs in Postman

https://deeppatel23.medium.com/crud-operations-in-spring-boot-and-mysql-rest-apis-9ca0c15bdc73 7/16
14/04/2024, 22:04 CRUD operations in Spring Boot and MySql (Rest APIs) | by Deep Patel | Medium
Save employee details

Retrieve employee details

Update employee details

https://deeppatel23.medium.com/crud-operations-in-spring-boot-and-mysql-rest-apis-9ca0c15bdc73 8/16
14/04/2024, 22:04 CRUD operations in Spring Boot and MySql (Rest APIs) | by Deep Patel | Medium

Delete employee

I hope you guys understood the basis of creating Rest APIs in spring boot and performing CRUD operations in the MySql
database. If you have any doubts, do ask them in the comments below, I am happy to answer all.

Check out the complete source code.

https://deeppatel23.medium.com/crud-operations-in-spring-boot-and-mysql-rest-apis-9ca0c15bdc73 9/16

You might also like