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:
JDK 11 or later
Maven
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.io 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:
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:
packagecom.example.cruddemo.controller;importcom.example.cruddemo.model.User;importcom.example.cruddemo.repository.UserRepository;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.http.ResponseEntity;importorg.springframework.web.bind.annotation.*;importjava.util.List;@RestController@RequestMapping("/api/users")publicclassUserController { @AutowiredprivateUserRepository userRepository;// Get all users @GetMappingpublicList<User> getAllUsers() {returnuserRepository.findAll(); }// Get a single user by ID @GetMapping("/{id}")publicResponseEntity<User> getUserById(@PathVariableLong id) { User user = userRepository.findById(id).orElseThrow(() -> new ResourceNotFoundException("User not found with id: " + id));
returnResponseEntity.ok(user); }// Create a new user @PostMappingpublicUsercreateUser(@RequestBodyUser user) {returnuserRepository.save(user); }// Update an existing user @PutMapping("/{id}")publicResponseEntity<User> updateUser(@PathVariableLong id, @RequestBodyUser userDetails) { User user = userRepository.findById(id).orElseThrow(() -> new ResourceNotFoundException("User not found with id: " + id));
user.setName(userDetails.getName());user.setEmail(userDetails.getEmail());User updatedUser =userRepository.save(user);returnResponseEntity.ok(updatedUser); }// Delete a user @DeleteMapping("/{id}")publicResponseEntity<Void> deleteUser(@PathVariableLong id) { User user = userRepository.findById(id).orElseThrow(() -> new ResourceNotFoundException("User not found with id: " + id));
userRepository.delete(user);returnResponseEntity.noContent().build(); }}
Step 6: Handle Exceptions
Create a custom exception and exception handler for resource not found cases. In the controller package, add the following classes:
(Optional) Create a data.sql file in the src/main/resources directory to seed the database with initial data:
INSERT INTO user (name, email) VALUES ('John Doe', 'john.doe@example.com');INSERT INTO user (name, email) VALUES ('Jane Smith', 'jane.smith@example.com');
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:
curl-XGEThttp://localhost:8080/api/users
Get user by ID:
curl-XGEThttp://localhost:8080/api/users/1
Create a new user:
curl -X POST http://localhost:8080/api/users -H "Content-Type: application/json" -d '{"name":"Alice Brown","email":"alice.brown@example.com"}'
Update a user:
curl -X PUT http://localhost:8080/api/users/1 -H "Content-Type: application/json" -d '{"name":"John Doe Jr.","email":"john.doe.jr@example.com"}'
Delete a user:
curl-XDELETEhttp://localhost:8080/api/users/1
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!