Java Records CRUD (Create, Read, Update, Delete) Example

1. Introduction

This blog post provides an example of using Java records in a CRUD (Create, Read, Update, Delete) application. Java Records, introduced in Java 16, offer a concise way to model immutable data structures, making them ideal for representing entities in CRUD operations.

Definition

CRUD operations are the four basic functions of persistent storage in software development. Java Records simplify the implementation of these operations by providing a clear and concise way to define data structures.

2. Program Steps

1. Define a Java Record to represent an entity.

2. Create a basic service class to perform CRUD operations.

3. Demonstrate each CRUD operation.

3. Code Program

import java.util.*;

// Record representing an entity
public record Product(int id, String name, double price) {}

// Service class to perform CRUD operations
class ProductService {
    private final Map<Integer, Product> products = new HashMap<>();

    // Create a new product
    public void createProduct(Product product) {
        products.put(product.id(), product);
    }

    // Read a product by ID
    public Product readProduct(int id) {
        return products.get(id);
    }

    // Update an existing product
    public void updateProduct(int id, Product updatedProduct) {
        products.put(id, updatedProduct);
    }

    // Delete a product by ID
    public void deleteProduct(int id) {
        products.remove(id);
    }
}

public class Main {
    public static void main(String[] args) {
        ProductService service = new ProductService();

        // Create
        service.createProduct(new Product(1, "Laptop", 1500.0));

        // Read
        System.out.println("Read: " + service.readProduct(1));

        // Update
        service.updateProduct(1, new Product(1, "Laptop", 1200.0));
        System.out.println("Updated: " + service.readProduct(1));

        // Delete
        service.deleteProduct(1);
        System.out.println("Deleted: " + service.readProduct(1));
    }
}

Output:

Read: Product[id=1, name=Laptop, price=1500.0]
Updated: Product[id=1, name=Laptop, price=1200.0]
Deleted: null

Explanation:

1. The Product record represents an entity with id, name, and price.

2. The ProductService class implements CRUD operations using a HashMap to store Product instances.

3. The createProduct method adds a new Product to the map.

4. The readProduct method retrieves a Product by its id.

5. The updateProduct method updates an existing Product in the map.

6. The deleteProduct method removes a Product from the map by its id.

7. In the main method, each CRUD operation is demonstrated with appropriate outputs, showing the effectiveness of using Java Records in CRUD applications.


Comments