Skip to main content

How to Perform CRUD Operations via API Using Java, Spring Boot, and MySQL

Introduction

In this blog post, I will guide you through the process of performing basic CRUD (Create, Read, Update, Delete) operations using Java, Spring Boot, and MySQL. CRUD operations are fundamental to any application that deals with persistent storage, and understanding them is crucial for any software developer. By the end of this tutorial, you will have a working RESTful API that can handle CRUD operations for a simple User entity.

Setting Up the Environment

Before we start coding, let's set up our development environment.

Prerequisites:

Java Development Kit (JDK): Make sure you have JDK 8 or later installed. You can download it from here (https://www.oracle.com/java/technologies/javase-downloads.html)
Integrated Development Environment (IDE): I recommend using STS(Spring Tool Suite) or Eclipse. You can download STS from here (https://spring.io/tools)
MySQL Database: Install MySQL and set up a new database. You can download MySQL from here (https://dev.mysql.com/downloads/)

Creating a Spring Boot Project

We will use STS(IDE) for developing Spring Boot Application using a Spring Starter Project or you can use a Spring Initializr(Website) to generate our Spring Boot project. Go to Spring Initializr and generate a project with the following dependencies:

Spring Web
Spring Data JPA
MySQL Driver
Spring Dev Tools
If you use STS then just add above dependencies and open it in STS directly or if you use Spring Initializr(Website) Once you download the project, unzip it and open it in your IDE.

Configuring the Application

Next, we need to configure our Spring Boot application to connect to MySQL. Open src/main/resources/application.properties and add the following configuration:

spring.application.name=user_app
spring.datasource.url=jdbc:mysql://localhost:3306/yourdatabase
spring.datasource.username=root
spring.datasource.password=yourpassword

spring.jpa.show-sql=false

server.port=8080
Replace yourdatabase, root, and yourpassword with your actual database name, username, and password.

Creating the Model(Data Class)

Now, let's create our User entity. Create a new class User in the com.user.entity package:

package com.user.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.IDENTITY)
private Long id;
private String name;
private String email;

// Getters and Setters
public Long getId() {
return id;
}

public void setId(Long 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;
}
}

Creating the Repository

Next, create a repository interface for User:

package com.user.repository;

import org.springframework.data.jpa.repository.JpaRepository;

import com.user.entity.User;

public interface UserRepo extends JpaRepository<User, Long> {

}

Creating the Service

We will now create a service to handle business logic. Create a new class UserService:

package com.user.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.user.entity.User;
import com.user.repository.UserRepo;

@Service
public class UserService {
    @Autowired
    private UserRepo userRepo;

    public List<User> getAllUsers() {
        return userRepo.findAll();
    }

    public User getUserById(Long id) {
        return userRepo.findById(id).orElse(null);
    }

    public User createUser(User user) {
        return userRepo.save(user);
    }

    public User updateUser(Long id, User userDetails) {
        User user = userRepo.findById(id).orElse(null);
        if (user != null) {
            user.setName(userDetails.getName());
            user.setEmail(userDetails.getEmail());
            return userRepo.save(user);
        }
        return null;
    }

    public void deleteUser(Long id) {
    userRepo.deleteById(id);
    }

}

Creating the Controller

Now, let's create a REST controller to expose our CRUD operations via HTTP endpoints. Create a new class UserController:

package com.user.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.user.entity.User;
import com.user.service.UserService;

@RestController
@RequestMapping("/user")
public class UserController {

@Autowired
private UserService userService;
//http://localhost:8080
@PostMapping("/add")
public ResponseEntity<String> createUser(@RequestBody User user) {
userService.createUser(user);
return new ResponseEntity<>("User saved successfully!", HttpStatus.OK);
}

@PutMapping("/modify")
public ResponseEntity<String> updateUser(@RequestBody User user) {
Long id = user.getId(); // Get the ID from the request body
if (id == null || userService.getUserById(id) == null) {
return new ResponseEntity<>("User not found!", HttpStatus.NOT_FOUND);
}
userService.createUser(user);
return new ResponseEntity<>("User updated successfully!", HttpStatus.OK);
}

@DeleteMapping("/remove")
public ResponseEntity<String> deleteUser(@RequestBody User user) {
Long id = user.getId(); // Get the ID from the request body
if (id == null || userService.getUserById(id) == null) {
return new ResponseEntity<>("User not found!", HttpStatus.NOT_FOUND);
}
userService.deleteUser(id);// Delete the user by ID
return new ResponseEntity<>("User deleted successfully!", HttpStatus.OK);
}

@GetMapping("/all")
public List<User> getAllUsers() {
return userService.getAllUsers();
}

@GetMapping("/fetch/{id}")
public User getUserById(@PathVariable Long id) {
return userService.getUserById(id);
}
}


Testing the API

To test our API, we can use Postman or any other API testing tool. Here are the endpoints we have created:

GET /user/all - Get all users
GET /user/fetch/{id} - Get user by ID
POST /user/add - Create a new user
PUT /user/modify - Update an existing user
DELETE /user/remove - Delete a user

Conclusion

In this tutorial, we have successfully created a RESTful API for performing CRUD operations using Java, Spring Boot, and MySQL. This API can serve as a foundation for more complex applications. By following this guide, you should now have a good understanding of how to set up and implement basic CRUD functionality in a Spring Boot application.

If you have any questions or need further clarification, feel free to leave a comment below. Happy coding!

Comments