Spring Boot Gradle CRUD Example - CRUD REST APIs
author : Sai K
In this tutorial, we will create a simple Spring Boot application using Gradle that performs CRUD
(Create, Read,
Update, Delete) operations on a Student entity. We will use Spring Data JPA to
interact with a relational
database.
Prerequisites
- JDK 17 or later
- Gradle
- Spring Boot (version 3.2+ recommended)
- IDE (IntelliJ IDEA, Eclipse, etc.)
- A relational database (e.g., H2, MySQL, PostgreSQL)
Step 1: Set Up a Spring Boot Project Using Spring Initializr
Use Spring Initializr to generate a new Spring Boot project with the following configuration:
- Project: Gradle Project
- Language: Java
- Spring Boot: 3.2.x
- Dependencies: Spring Web, Spring Data JPA, H2 Database (or your preferred database)
Download the generated project, unzip it, and open it in your IDE.
Project Structure
The basic structure of a Spring Boot project with Gradle looks like this:
my-spring-boot-app/
├── build.gradle
├── settings.gradle
├── src/
│ ├── main/
│ │ ├── java/
│ │ │ └── com/example/demo/
│ │ │ └── DemoApplication.java
│ │ │ └── model/
│ │ │ └── Student.java
│ │ │ └── repository/
│ │ │ └── StudentRepository.java
│ │ │ └── service/
│ │ │ └── StudentService.java
│ │ │ └── controller/
│ │ │ └── StudentController.java
│ │ └── resources/
│ │ ├── application.properties
│ └── test/
│ └── java/
│ └── com/example/demo/
│ └── DemoApplicationTests.java
└── gradlew
└── gradlew.bat
└── gradle/
└── wrapper/
└── gradle-wrapper.properties
Step 2: Configuring build.gradle
Open the build.gradle file and configure it as follows:
plugins {
id 'org.springframework.boot' version '3.2.0'
id 'io.spring.dependency-management' version '1.1.0'
id 'java'
}
group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '17'
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
runtimeOnly 'com.h2database:h2' // Use H2 database for simplicity
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
test {
useJUnitPlatform()
}
Step 3: Create the Student Entity
Create a Java class named Student in the src/main/java/com/example/demo/model directory.
package com.example.demo.model;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
@Entity
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private int age;
// Constructors, getters, and setters
public Student() {
}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
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 int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
Step 4: Create the Student Repository
Create a repository interface named StudentRepository in the
src/main/java/com/example/demo/repository
directory.
package com.example.demo.repository;
import com.example.demo.model.Student;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface StudentRepository extends JpaRepository {
}
Step 5: Create the Student Service
Create a service class named StudentService in the src/main/java/com/example/demo/service directory.
package com.example.demo.service;
import com.example.demo.model.Student;
import com.example.demo.repository.StudentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
@Service
public class StudentService {
@Autowired
private StudentRepository studentRepository;
public List getAllStudents() {
return studentRepository.findAll();
}
public Optional getStudentById(Long id) {
return studentRepository.findById(id);
}
public Student createStudent(Student student) {
return studentRepository.save(student);
}
public Optional updateStudent(Long id, Student student) {
return studentRepository.findById(id).map(existingStudent -> {
existingStudent.setName(student.getName());
existingStudent.setAge(student.getAge());
return studentRepository.save(existingStudent);
});
}
public void deleteStudent(Long id) {
studentRepository.deleteById(id);
}
}
Step 6: Create the REST Controller
Create a controller class named StudentController in the src/main/java/com/example/demo/controller directory.
package com.example.demo.controller;
import com.example.demo.model.Student;
import com.example.demo.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Optional;
@RestController
@RequestMapping("/students")
public class StudentController {
@Autowired
private StudentService studentService;
@GetMapping
public List getAllStudents() {
return studentService.getAllStudents();
}
@GetMapping("/{id}")
public Optional getStudentById(@PathVariable Long id) {
return studentService.getStudentById(id);
}
@PostMapping
public Student createStudent(@RequestBody Student student) {
return studentService.createStudent(student);
}
@PutMapping("/{id}")
public Optional updateStudent(@PathVariable Long id, @RequestBody Student student) {
return studentService.updateStudent(id, student);
}
@DeleteMapping("/{id}")
public void deleteStudent(@PathVariable Long id) {
studentService.deleteStudent(id);
}
}
Step 7: Configure the Database
Open the src/main/resources/application.properties file and configure the H2 database.
# src/main/resources/application.properties
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=password
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.h2.console.enabled=true
Step 8: Running the Application
Using IDE
You can run the application directly from your IDE. Look for a "Run" or "Debug" option for the
DemoApplication
class.
Using Gradle
Alternatively, you can run the application using the Gradle wrapper. Open a terminal in the project
root directory
and run the following command:
For Unix/Linux/macOS:
./gradlew bootRun
For Windows:
gradlew.bat bootRun
Step 9: Verify CRUD Operations
Use a tool like Postman or curl to test the endpoints.
- Create a Student:
- URL: http://localhost:8080/students
- Method: POST
- Body:
{
"name": "John Doe",
"age": 20
}
- URL: http://localhost:8080/students
- Method: GET
- URL: http://localhost:8080/students/1
- Method: GET
- URL: http://localhost:8080/students/1
- Method: PUT
- Body:
{
"name": "Jane Doe",
"age": 21
}
- URL: http://localhost:8080/students/1
- Method: DELETE
You should see the correct responses and verify that the data is stored, retrieved, updated, and
deleted
from the H2 database.
Conclusion
In this tutorial, you have learned how to create a Spring Boot application using Gradle that performs
CRUD
operations on a Student entity. We covered:
- Setting up a Spring Boot project with Gradle.
- Configuring the
build.gradle
file. - Creating a Student entity, repository, service, and REST controller.
- Configuring the H2 database.
- Running the application and verifying CRUD operations using Postman or curl.
By following these steps, you can easily set up and manage Spring Boot projects using Gradle and
perform
CRUD operations on a relational database.