DEV Community

Cover image for Building a User CRUD Application with Spring Boot and Docker
Tandap Noel Bansikah
Tandap Noel Bansikah

Posted on • Updated on

Building a User CRUD Application with Spring Boot and Docker

Introduction

Spring Boot is a framework that simplifies the development of production-ready applications using the Spring framework. It provides a set of tools and conventions to help you build applications quickly and efficiently. With Spring Boot, you can easily create stand-alone, production-grade applications with minimal configuration.

This guide will walk you through creating a simple User CRUD (Create, Read, Update, Delete) application using Spring Boot. Weโ€™ll also containerize the application with Docker to ensure consistency across different environments.

Prerequisites

Ensure you have the following installed:

  • Java JDK 17 or higher
  • Maven
  • Docker
  • Git

Step 1: Create a New Spring Boot Project

Generate the Project

Use Spring Initializr to generate a new Spring Boot project:

  • Project: Maven Project
  • Language: Java
  • Spring Boot: 3.3.3
  • Group: com.example
  • Artifact: user-crud
  • Dependencies: Spring Web, Spring Data JPA, H2 Database

Click "Generate" to download the project, then unzip it.

Navigate to the Project Directory

cd user-crud
Enter fullscreen mode Exit fullscreen mode

Step 2: Define the User Entity

Create the Entity Class

Create a new Java class named User.java inside src/main/java/com/example/usercrud:

package com.example.usercrud;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Table(name = "users")
@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;
    }
}
Enter fullscreen mode Exit fullscreen mode

Step 3: Create the User Repository

Create the Repository Interface

Create a new Java interface named UserRepository.java inside src/main/java/com/example/usercrud:

package com.example.usercrud;

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

public interface UserRepository extends JpaRepository<User, Long> {
}
Enter fullscreen mode Exit fullscreen mode

Step 4: Create the User Controller

Create the REST Controller

Create a new Java class named UserController.java inside src/main/java/com/example/usercrud:

package com.example.usercrud;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
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 UserRepository userRepository;

    @PostMapping
    public ResponseEntity<User> createUser(@RequestBody User user) {
        User savedUser = userRepository.save(user);
        return new ResponseEntity<>(savedUser, HttpStatus.CREATED);
    }

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

    @GetMapping("/{id}")
    public ResponseEntity<User> getUserById(@PathVariable Long id) {
        Optional<User> user = userRepository.findById(id);
        return user.map(ResponseEntity::ok).orElseGet(() -> ResponseEntity.notFound().build());
    }

    @PutMapping("/{id}")
    public ResponseEntity<User> updateUser(@PathVariable Long id, @RequestBody User user) {
        if (!userRepository.existsById(id)) {
            return ResponseEntity.notFound().build();
        }
        user.setId(id);
        User updatedUser = userRepository.save(user);
        return ResponseEntity.ok(updatedUser);
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteUser(@PathVariable Long id) {
        if (!userRepository.existsById(id)) {
            return ResponseEntity.notFound().build();
        }
        userRepository.deleteById(id);
        return ResponseEntity.noContent().build();
    }
}
Enter fullscreen mode Exit fullscreen mode

Configuring H2 Database

H2 is a popular, open-source, in-memory relational database management system written in Java. It is designed to be lightweight, fast, and easy to integrate, making it a good choice for development, testing, and educational purposes. H2 can run in various modes, including as an in-memory database or as a persistent database stored on disk.

Configuration

To configure the database goto /src/main/resources
/application.properties

spring.application.name=usercrud

server.port=8080

spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.url=jdbc:h2:file:~/userdb
spring.datasource.username=sa
spring.datasource.password=password
spring.jpa.hibernate.ddl-auto=update

spring.h2.console.enabled=true
spring.h2.console.path=/h2
Enter fullscreen mode Exit fullscreen mode

Access H2 Console: If you enabled the H2 console, you can access it via http://localhost:8080/h2. You need to log in with the JDBC URL, username, and password specified in your configuration.

JDBC URL: jdbc:h2:file:~/userdb
Username: sa
Password: password

Step 5: Create a Dockerfile

Add a Dockerfile

Create a file named Dockerfile in the root directory of your project with the following content:

# Use a base image with Java 17
FROM openjdk:17-jdk-slim

# Set the working directory
WORKDIR /app

# Copy the jar file from the target directory
COPY target/user-crud-0.0.1-SNAPSHOT.jar app.jar

# Expose port 8080
EXPOSE 8080

# Run the application
ENTRYPOINT ["java", "-jar", "/app/app.jar"]
Enter fullscreen mode Exit fullscreen mode

Build the Docker Image

First, package your application with Maven:

./mvnw clean package
Enter fullscreen mode Exit fullscreen mode

Then build the Docker image:

docker build -t user-crud .
Enter fullscreen mode Exit fullscreen mode

Step 6: Run the Docker Container

Run the Container

Use the following command to run your Docker container:

docker run -p 8080:8080 user-crud
Enter fullscreen mode Exit fullscreen mode

Verify the Application

Visit http://localhost:8080/api/users to ensure the application is running correctly within the Docker container. You can use tools like curl or Postman to test the CRUD endpoints.

Conclusion

Youโ€™ve successfully created a simple User CRUD application with Spring Boot, containerized it using Docker, and verified its operation. This setup allows you to deploy and manage your application consistently across different environments, you can extend this example with additional features or integrate it into a larger system.
Feel free to reach out with your questions... Happy Coding!

For more information, refer to:

Also want to see the sample full-stack application frontend and backend visit Fullstack Source Code

Top comments (0)