Table of contents
1.
Introduction
2.
Explanation of each operation
2.1.
1. Create (POST)
2.2.
2. Read (GET)
2.3.
3. Update (PUT)
2.4.
4. Delete (DELETE)
3.
CRUD Operations for Student Management System in Java
3.1.
Implementation
4.
Frequently Asked Questions
4.1.
What is the purpose of CRUD operations in Java? 
4.2.
Can CRUD operations be performed without using the Spring framework? 
4.3.
Are CRUD operations limited to relational databases? 
5.
Conclusion
Last Updated: Dec 19, 2024
Easy

CRUD Operations in Java

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

CRUD operations are the foundation of data manipulation in Java applications. These operations allow you to interact with a database or data storage system, which helps you to create new records, retrieve existing data, update information, & delete entries when necessary. Let's understand the meaning of these CRUD operations : 

CRUD operations allow you to interact with a database or data storage system that enables you to manage & manipulate data effectively. 

CRUD Operations in Java

In this article, we'll learn about CRUD operations in Java, discussing each operation in detail, with code examples, & showing their implementation in a real-world scenario. 

In software development, working or manipulating data is an essential task. Even if you're building a simple application or a complex system, you'll need to perform basic data manipulation operations.

These are the CRUD operations in Java:

1. Create (POST)

The Create operation, also known as POST, is used to insert new data into a database. In Java, this is typically accomplished by sending an HTTP POST request to a server, along with the data to be added. The server then processes the request & creates a new record in the database based on the provided information.

2. Read (GET)

The Read operation, or GET, is used to retrieve data from a database. When you send an HTTP GET request to a server, it queries the database & returns the requested data. This operation is essential for displaying information to users, such as fetching a list of students in a Student Management System.

3. Update (PUT)

The Update operation, represented by PUT, is used to modify existing data in a database. When you send an HTTP PUT request to a server, along with the updated data, it locates the corresponding record in the database & applies the specified changes. This operation allows you to keep your data accurate & up to date.

4. Delete (DELETE)

The Delete operation, as the name suggests, is used to remove data from a database. By sending an HTTP DELETE request to a server, specifying the record to be deleted, it locates & eliminates the corresponding entry from the database. This operation is crucial for maintaining data integrity & removing unnecessary or outdated information.

Explanation of each operation

Now, let’s understand these functions in more detail with proper examples: 

1. Create (POST)

To create a new record in a database using Java, you typically send an HTTP POST request to a server endpoint. The request includes the data to be added, often in JSON format. Let’s discuss an example of how to create a new student record using the Java HttpClient:

HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
        .uri(URI.create("http://example.com/students"))
        .header("Content-Type", "application/json")
        .POST(HttpRequest.BodyPublishers.ofString("{\"name\":\"Rahul Singh\",\"age\":20}"))
        .build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

 

In this example, we create an instance of the HttpClient & build an HTTP POST request. We specify the server endpoint URL, set the Content-Type header to "application/json", & include the student data in the request body. Finally, we send the request & handle the response accordingly.

2. Read (GET)

To retrieve data from a database, you send an HTTP GET request to a server endpoint. The server processes the request, queries the database, & returns the requested data. Here's an example of how to fetch a student record by ID using the Java HttpClient:

HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
        .uri(URI.create("http://example.com/students/1"))
        .GET()
        .build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
String studentData = response.body();


In this example, we create an HttpClient & build an HTTP GET request. We specify the server endpoint URL, including the ID of the student record we want to retrieve. We send the request & handle the response, which contains the requested student data.

3. Update (PUT)

To update an existing record in a database, you send an HTTP PUT request to a server endpoint, along with the updated data. The server locates the corresponding record & applies the specified changes. Let’s see an example of how to update a student record using the Java HttpClient:

HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
        .uri(URI.create("http://example.com/students/1"))
        .header("Content-Type", "application/json")
        .PUT(HttpRequest.BodyPublishers.ofString("{\"name\":\"Rinki Deka\",\"age\":21}"))
        .build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

 

In this example, we create an HttpClient & build an HTTP PUT request. We specify the server endpoint URL, including the ID of the student record we want to update. We set the Content-Type header to "application/json" & include the updated student data in the request body. We send the request & handle the response accordingly.

4. Delete (DELETE)

To delete a record from a database, you send an HTTP DELETE request to a server endpoint, specifying the ID of the record to be deleted. The server locates & removes the corresponding record from the database. 

An example of how to delete a student record using the Java HttpClient:

HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
        .uri(URI.create("http://example.com/students/1"))
        .DELETE()
        .build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());


In this example, we create an HttpClient & build an HTTP DELETE request. We specify the server endpoint URL, including the ID of the student record we want to delete. We send the request & handle the response accordingly.

CRUD Operations for Student Management System in Java

To show and understand the practical application of CRUD operations in Java, let's build a simple Student Management System. This system will allow us to create, read, update, & delete student records using a RESTful API. We'll use the Java Spring Boot framework to create the API endpoints & interact with a database.

First, let's define the Student model class:

public class Student {
    private Long id;
    private String name;
    private int age;
    // Constructors, getters, and setters
}

Next, we'll create a StudentRepository interface that extends the JpaRepository interface provided by Spring Data JPA. This interface will handle the database operations for us:

public interface StudentRepository extends JpaRepository<Student, Long> {
}

Now, let's implement the CRUD operations in the StudentController class:

@RestController
@RequestMapping("/students")
public class StudentController {
    private final StudentRepository studentRepository;
    public StudentController(StudentRepository studentRepository) {
        this.studentRepository = studentRepository;
    }
    // Create operation
    @PostMapping
    public Student createStudent(@RequestBody Student student) {
        return studentRepository.save(student);
    }
    // Read operation
    @GetMapping("/{id}")
    public Student getStudentById(@PathVariable Long id) {
        return studentRepository.findById(id)
                .orElseThrow(() -> new ResourceNotFoundException("Student not found with id: " + id));
    }
  // Update operation
    @PutMapping("/{id}")
    public Student updateStudent(@PathVariable Long id, @RequestBody Student updatedStudent) {
        Student student = studentRepository.findById(id)
                .orElseThrow(() -> new ResourceNotFoundException("Student not found with id: " + id));
        student.setName(updatedStudent.getName());
        student.setAge(updatedStudent.getAge());
        return studentRepository.save(student);
    }
    // Delete operation
    @DeleteMapping("/{id}")
    public void deleteStudent(@PathVariable Long id) {
        Student student = studentRepository.findById(id)
                .orElseThrow(() -> new ResourceNotFoundException("Student not found with id: " + id));
        studentRepository.delete(student);
    }
}


In this StudentController class, we define the endpoints for each CRUD operation:

  • Create: The `createStudent` method handles the HTTP POST request to create a new student record. It receives the student data in the request body & saves it to the database using the `studentRepository.save()` method.
  • Read: The `getStudentById` method handles the HTTP GET request to retrieve a student record by ID. It uses the `studentRepository.findById()` method to fetch the student from the database. If the student is not found, it throws a `ResourceNotFoundException`.
  • Update: The `updateStudent` method handles the HTTP PUT request to update an existing student record. It receives the student ID & the updated student data in the request. It fetches the student from the database, updates its properties, & saves the changes using the `studentRepository.save()` method.
  • Delete: The `deleteStudent` method handles the HTTP DELETE request to delete a student record. It receives the student ID in the request, fetches the student from the database, & deletes it using the `studentRepository.delete()` method.

Implementation

To implement the Student Management System with CRUD operations in Java, we'll use the Spring Boot framework & the Spring Data JPA library for database integration. We'll also use Maven for dependency management.

First, let's set up the project structure & dependencies in the `pom.xml` file:

<project>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.0</version>
    </parent>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>runtime</scope>
        </dependency>
    </dependencies>
</project>

In this `pom.xml` file, we define the parent project as `spring-boot-starter-parent` & include the necessary dependencies for Spring Boot web, Spring Data JPA, & the H2 in-memory database.

Next, let's create the main application class:

@SpringBootApplication
public class StudentManagementApplication {
    public static void main(String[] args) {
        SpringApplication.run(StudentManagementApplication.class, args);
    }
}


The `@SpringBootApplication` annotation indicates that this is the main class of our Spring Boot application.

Now, let's define the `Student` entity class:

@Entity
public class Student {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;
    private int age;


    // Constructors, getters, and setters
}

The `Student` class is annotated with `@Entity` to indicate that it's a JPA entity. The `id` field is annotated with `@Id` & `@GeneratedValue` to specify that it's the primary key & should be automatically generated.

Next, we create the `StudentRepository` interface:

@Repository
public interface StudentRepository extends JpaRepository<Student, Long> {
}

The `StudentRepository` interface extends `JpaRepository`, which provides basic CRUD operations out of the box.

Finally, let's implement the `StudentController` class:

@RestController
@RequestMapping("/students")
public class StudentController {
    private final StudentRepository studentRepository;


    public StudentController(StudentRepository studentRepository) {
        this.studentRepository = studentRepository;
    }
    // CRUD operation methods (createStudent, getStudentById, updateStudent, deleteStudent)
}

The `StudentController` class is annotated with `@RestController` to indicate that it's a RESTful controller. The `@RequestMapping` annotation specifies the base URL path for the endpoints.

Inside the controller, we inject an instance of `StudentRepository` via constructor injection. The CRUD operation methods (createStudent, getStudentById, updateStudent, deleteStudent) are implemented as shown in the previous section.

With this setup, you can run the application & test the CRUD operations using tools like cURL or Postman.

For example, to create a new student, you can send a POST request to `http://localhost:8080/students` with the following JSON body:

{
    "name": "Rahul Singh",
    "age": 20
}

To retrieve a student by ID, you can send a GET request to `http://localhost:8080/students/{id}`, where `{id}` is the actual ID of the student.

Similarly, you can update a student by sending a PUT request to `http://localhost:8080/students/{id}` with the updated student data in the request body, & delete a student by sending a DELETE request to `http://localhost:8080/students/{id}`.

That's it! You now have a basic implementation of a Student Management System with CRUD operations in Java using Spring Boot & Spring Data JPA.

Frequently Asked Questions

What is the purpose of CRUD operations in Java? 

CRUD operations in Java allow developers to perform essential data manipulation tasks on a database or data storage system. They provide a standardized way to Create, Read, Update, & Delete records, enabling efficient management & maintenance of data within an application.

Can CRUD operations be performed without using the Spring framework? 

Yes, CRUD operations can be performed in Java without using the Spring framework. You can use other frameworks like Java EE (now Jakarta EE) or plain JDBC (Java Database Connectivity) to interact with a database & implement CRUD functionality. However, Spring Boot & Spring Data JPA provide a convenient & efficient way to handle CRUD operations with minimal boilerplate code.

Are CRUD operations limited to relational databases? 

No, CRUD operations are not limited to relational databases. They can be applied to various types of data storage systems, including NoSQL databases (e.g., MongoDB, Cassandra), file systems, or even in-memory data structures. The principles of Create, Read, Update, & Delete remain the same, regardless of the underlying storage mechanism.

Conclusion

In this article, we explained CRUD operations in Java & their importance in building robust & efficient applications. We learned that CRUD stands for Create, Read, Update, & Delete, representing the four fundamental functions for managing data in a database or storage system. We looked into each operation, understood their purpose & how to implement them with the help of Java. We provided code examples using the Java HttpClient to show how to send HTTP requests to perform CRUD operations on a server.

You can also check out our other blogs on Code360.

Live masterclass