DEV Community

Cover image for Spring Boot + MySQL + Spring Data JPA: A Beginner's Guide to REST API CRUD Operations
Abhishek Tiwari
Abhishek Tiwari

Posted on

Spring Boot + MySQL + Spring Data JPA: A Beginner's Guide to REST API CRUD Operations

Introduction:

In the world of modern web development, creating robust and scalable APIs is a fundamental task. Spring Boot, a powerful framework built on top of the Spring framework, makes it easier for developers to develop production-ready applications quickly.

In this blog, we will use service layer to handle business logic and interact with the repository. This approach promotes separation of concerns and enhances the maintainability and testability of the codebase. We will walk through the step-by-step process of setting up the development environment, configuring the MySQL database, creating the service layer, defining the application properties, and testing the API endpoints with sample code.

Spring Boot Project High-level Architecture Diagram:

The high-level architecture diagram depicts the flow of data and interactions within the Spring Boot application. It illustrates how frontend UI/Postman communicates with the Spring Boot API, which further coordinates with the service layer and Spring Data JPA to perform CRUD operations on the MySQL database.

Image description

Prerequisites:

  1. Basic understanding of Java and Spring Boot.
  2. Familiarity with MySQL database and SQL queries.
  3. Java Development Kit (JDK) installed (version 8 or higher).
  4. An Integrated Development Environment (IDE) like IntelliJ or Eclipse.

Step 1: Setting up the Project

Let's begin by creating a new Spring Boot project:
image

  1. Go to Spring Initializr (https://start.spring.io/) or use the IDE's project creation wizard to create a new Spring Boot project.
  2. Add the required dependencies:
    • Spring Web: Provides the necessary components for building web applications.
    • Spring Data JPA: Simplifies database access using JPA (Java Persistence API).
    • MySQL Driver: Allows Spring Boot to communicate with the MySQL database.
  3. Generate the project and import it into your IDE.

Step 2: Database Configuration

Now, let's configure the database to store our data. In this example, we will use MySQL:

  1. Install MySQL on your local machine if you haven't already. You can download it from the official website: https://dev.mysql.com/downloads/installer/.
  2. Create a new database and a table to store our data. You can use a MySQL client like phpMyAdmin or MySQL Workbench to create the database and table. For this example, let's create a table called "users" with columns "id," "name," and "email."

Step 3: Creating the Entity

In Spring Boot, an entity represents a table in the database. Let's create an entity class representing our "users" table:

// User.java
import javax.persistence.*;

@Entity
@Table(name = "users")
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;

    private String email;

    // Getters and setters 
}
Enter fullscreen mode Exit fullscreen mode

Step 4: Defining Application Properties

The application.properties (or application.yml) file allows us to configure various properties for our Spring Boot application, including database connection settings:

Create an "application.properties" file in the "src/main/resources" folder and add the following configuration:

# Database Configuration
spring.datasource.url=jdbc:mysql://localhost:3306/your_database_name
spring.datasource.username=your_database_username
spring.datasource.password=your_database_password
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

# Hibernate Configuration
spring.jpa.hibernate.ddl-auto=update
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect
Enter fullscreen mode Exit fullscreen mode

Ensure you replace "your_database_name," "your_database_username," and "your_database_password" with your actual MySQL database credentials.

Step 5: Creating the Repository

The repository interface provides the basic CRUD operations for our entity. Spring Data JPA automatically implements these operations for us:

// UserRepository.java
import org.springframework.data.jpa.repository.JpaRepository;

public interface UserRepository extends JpaRepository<User, Long> {

}
Enter fullscreen mode Exit fullscreen mode

Step 6: Implementing the Service Layer

The service layer contains the business logic and coordinates with the repository to perform database operations. Let's create the service class for our API:

// UserService.java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserService {

    @Autowired
    private UserRepository userRepository;

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

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

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

    public User updateUser(Long id, User user) {
        user.setId(id);
        return userRepository.save(user);
    }

    public void deleteUser(Long id) {
        userRepository.deleteById(id);
    }
}
Enter fullscreen mode Exit fullscreen mode

Step 7: Creating the Controller

The controller handles HTTP requests and invokes the service methods. It remains unchanged from the previous blog:

// UserController.java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

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

    @Autowired
    private UserService userService;

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

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

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

    @PutMapping("/{id}")
    public User updateUser(@PathVariable Long id, @RequestBody User user) {
        return userService.updateUser(id, user);
    }

    @DeleteMapping("/{id}")
    public void deleteUser(@PathVariable Long id) {
        userService.deleteUser(id);
    }
}
Enter fullscreen mode Exit fullscreen mode

Step 8: Running the Application

Now that we have implemented the service layer, let's run the Spring Boot application:

  1. Build the project using your IDE's build tools.
  2. Run the Spring Boot application.
  3. The application should start, and you should see log messages indicating a successful startup.

Step 9: Testing the API Endpoints

To test the API endpoints, we can use tools like Postman or cURL. Let's test each CRUD operation:

  1. Create a new user:
-   Endpoint: POST  [http://localhost:8080/api/users](http://localhost:8080/api/users)
-   Request Body: { "name": "John Doe", "email": "[john@example.com](mailto:john@example.com)" }
Enter fullscreen mode Exit fullscreen mode
  1. Get all users:
-   Endpoint: GET  [http://localhost:8080/api/users](http://localhost:8080/api/users)
Enter fullscreen mode Exit fullscreen mode
  1. Get a user by ID:
-   Endpoint: GET  [http://localhost:8080/api/users/1](http://localhost:8080/api/users/1)
Enter fullscreen mode Exit fullscreen mode
  1. Update a user:
-   Endpoint: PUT  [http://localhost:8080/api/users/1](http://localhost:8080/api/users/1)
-   Request Body: { "name": "Updated Name", "email": "[updated@example.com](mailto:updated@example.com)" }
Enter fullscreen mode Exit fullscreen mode
  1. Delete a user:
-   Endpoint: DELETE  [http://localhost:8080/api/users/1](http://localhost:8080/api/users/1)
Enter fullscreen mode Exit fullscreen mode

Top comments (0)