Building a CRUD REST API with Spring Boot and MySQL: A Beginner's Guide

Building a CRUD REST API with Spring Boot and MySQL: A Beginner's Guide

Creating a CRUD (Create, Read, Update, Delete) REST API with Spring Boot and MySQL is a foundational task for any Java developer. This guide will walk you through the process step by step, providing code examples and explanations along the way.

Prerequisites

Before we begin, ensure you have the following installed on your system:

  1. Java Development Kit (JDK) 8 or higher

  2. Apache Maven

  3. MySQL Server

  4. An IDE like IntelliJ IDEA or Eclipse

Step 1: Setting Up the Spring Boot Project

1.1 Create a New Spring Boot Project

You can create a new Spring Boot project using Spring Initializr (https://start.spring.io/). Select the following dependencies:

  • Spring Web

  • Spring Data JPA

  • MySQL Driver

Alternatively, you can generate the project using the following dependencies in your pom.xml:

<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-web</artifactId>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

1.2 Configure the Application Properties

Configure the database connection in the application.properties file located in src/main/resources:

spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
spring.datasource.password=root
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true

Replace mydb with your database name, and update the username and password accordingly.

Step 2: Define the Entity

Create a Java class to represent the entity in the database. For this example, we'll use a simple User entity.

2.1 Create the User Entity

package com.example.demo.model;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.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;
    }
}

Step 3: Create the Repository

The repository layer will handle database operations. Spring Data JPA provides a convenient way to create repositories by extending JpaRepository.

3.1 Create the UserRepository

package com.example.demo.repository;

import com.example.demo.model.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

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

Step 4: Create the Service Layer

The service layer contains the business logic of the application. We'll create a UserService class to manage user-related operations.

4.1 Create the UserService

package com.example.demo.service;

import com.example.demo.model.User;
import com.example.demo.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 userRepository;

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

    public Optional<User> getUserById(Long id) {
        return userRepository.findById(id);
    }

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

    public User updateUser(Long id, User userDetails) {
        User user = userRepository.findById(id).orElseThrow(() -> new RuntimeException("User not found with id " + id));
        user.setName(userDetails.getName());
        user.setEmail(userDetails.getEmail());
        return userRepository.save(user);
    }

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

Step 5: Create the Controller

The controller layer handles HTTP requests and responses. We'll create a UserController to manage user-related endpoints.

5.1 Create the UserController

package com.example.demo.controller;

import com.example.demo.model.User;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

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

@RestController
@RequestMapping("/api/users")
public class UserController {

    @Autowired
    private UserService userService;

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

    @GetMapping("/{id}")
    public ResponseEntity<User> getUserById(@PathVariable Long id) {
        Optional<User> user = userService.getUserById(id);
        if (user.isPresent()) {
            return ResponseEntity.ok(user.get());
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    @PostMapping
    public User createUser(@RequestBody User user) {
        return userService.createUser(user);
    }

    @PutMapping("/{id}")
    public ResponseEntity<User> updateUser(@PathVariable Long id, @RequestBody User userDetails) {
        try {
            User updatedUser = userService.updateUser(id, userDetails);
            return ResponseEntity.ok(updatedUser);
        } catch (RuntimeException e) {
            return ResponseEntity.notFound().build();
        }
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteUser(@PathVariable Long id) {
        userService.deleteUser(id);
        return ResponseEntity.noContent().build();
    }
}

Step 6: Run the Application

With everything set up, you can now run the application. Navigate to the main application class and run it as a Java application.

package com.example.demo;

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

@SpringBootApplication
public class DemoApplication {

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

Step 7: Test the API

You can use tools like Postman or curl to test the API endpoints.

7.1 Create a User

curl -X POST -H "Content-Type: application/json" -d '{"name":"John Doe", "email":"john.doe@example.com"}' http://localhost:8080/api/users

7.2 Get All Users

curl -X GET http://localhost:8080/api/users

7.3 Get User by ID

curl -X GET http://localhost:8080/api/users/1

7.4 Update a User

curl -X PUT -H "Content-Type: application/json" -d '{"name":"John Smith", "email":"john.smith@example.com"}' http://localhost:8080/api/users/1

7.5 Delete a User

curl -X DELETE http://localhost:8080/api/users/1

Congratulations! You've successfully built a CRUD REST API with Spring Boot and MySQL. This guide provided a simple example to help you understand the basic concepts. You can now extend this application with more features, improve error handling, and add security.

Did you find this article valuable?

Support Nikhil Soman Sahu by becoming a sponsor. Any amount is appreciated!