Building a CRUD Application with Spring Boot

Spring Boot is a powerful framework for building Java-based web applications. One of its most common uses is to create RESTful APIs that interact with databases. This guide will walk you through creating a simple CRUD (Create, Read, Update, Delete) application using Spring Boot.

Prerequisites

Before you start, ensure you have the following installed:

  1. JDK 11 or later

  2. Maven

  3. An IDE like IntelliJ IDEA or Eclipse

Setting Up the Project

Step 1: Initialize a Spring Boot Project

You can use the Spring Initializr to generate your Spring Boot project. Go to start.spring.ioarrow-up-right and create a project with the following specifications:

  • Project: Maven

  • Language: Java

  • Spring Boot: 2.5.4 or later

  • Group: com.example

  • Artifact: crud-demo

  • Dependencies: Spring Web, Spring Data JPA, H2 Database, Lombok

Download the generated project and unzip it. Open the project in your IDE.

Step 2: Project Structure

Your project structure should look something like this:

Creating the CRUD Application

Step 3: Define the Entity

Create a new package model and define your entity class User:

Here, we use Lombok annotations (@Data, @NoArgsConstructor, @AllArgsConstructor) to generate boilerplate code like getters, setters, and constructors.

Step 4: Create the Repository

Create a new package repository and define the repository interface:

The UserRepository extends JpaRepository, which provides CRUD operations for the User entity.

Step 5: Create the Controller

Create a new package controller and define the controller class:

Step 6: Handle Exceptions

Create a custom exception and exception handler for resource not found cases. In the controller package, add the following classes:

ResourceNotFoundException.java:

GlobalExceptionHandler.java:

Step 7: Configure the Application

Open src/main/resources/application.properties and configure the H2 database:

Step 8: Seed the Database

(Optional) Create a data.sql file in the src/main/resources directory to seed the database with initial data:

Running the Application

Run the application by executing the CrudDemoApplication class. Your application should be accessible at http://localhost:8080.

Testing the Endpoints

Use a tool like Postman or curl to test the endpoints:

  • Get all users:

  • Get user by ID:

  • Create a new user:

  • Update a user:

  • Delete a user:

Conclusion

You've now built a complete CRUD application with Spring Boot. This basic structure can be expanded with more features, such as authentication, validation, and advanced querying. Spring Boot's simplicity and power make it an excellent choice for developing RESTful APIs. Happy coding!

Last updated