search
HomeJavajavaTutorialBuilding a User CRUD Application with Spring Boot and Docker

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 11 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.2.0
  • 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

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;

@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 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> {
}
</user>

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();
    }
}
</void></user></user></user></user></user>

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 11
FROM openjdk:11-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"]

Build the Docker Image

First, package your application with Maven:

./mvnw clean package

Then build the Docker image:

docker build -t user-crud .

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

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:

  • Spring Boot Documentation
  • Docker Documentation

The above is the detailed content of Building a User CRUD Application with Spring Boot and Docker. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to elegantly obtain entity class variable names to build database query conditions?How to elegantly obtain entity class variable names to build database query conditions?Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How to use the Redis cache solution to efficiently realize the requirements of product ranking list?How to use the Redis cache solution to efficiently realize the requirements of product ranking list?Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

How to safely convert Java objects to arrays?How to safely convert Java objects to arrays?Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

How do I convert names to numbers to implement sorting and maintain consistency in groups?How do I convert names to numbers to implement sorting and maintain consistency in groups?Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to set the default run configuration list of SpringBoot projects in Idea for team members to share?How to set the default run configuration list of SpringBoot projects in Idea for team members to share?Apr 19, 2025 pm 11:24 PM

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools