Java Records with Spring Boot CRUD Example

1. Introduction

This blog post demonstrates how to implement a CRUD (Create, Read, Update, Delete) application in Spring Boot using Java Records and H2 database. Java Records, introduced in Java 16, offer a concise way to create data classes, which we'll integrate with Spring Boot to build a simple but effective CRUD application.

Definition

CRUD operations are essential in most web applications, allowing for creating, reading, updating, and deleting data. Java Records provides an immutable data model, which is ideal for representing entities in such operations. The H2 database is an in-memory database, perfect for development and testing.

2. Program Steps

1. Create a Spring Boot project with H2 database dependency.

2. Define Java Records for entity and DTO (Data Transfer Object).

3. Implement a JPA repository for database operations.

4. Develop a service layer for business logic.

5. Create a controller to handle HTTP requests.

3. Code Program

// Entity class
@Entity
public record BookEntity(@Id @GeneratedValue Long id, String title, String author) {}

// DTO class
public record BookDTO(Long id, String title, String author) {}

// Repository
@Repository
public interface BookRepository extends JpaRepository<BookEntity, Long> {}

// Service
@Service
public class BookService {
    private final BookRepository repository;

    @Autowired
    public BookService(BookRepository repository) {
        this.repository = repository;
    }

    public BookDTO createBook(BookDTO bookDTO) {
        BookEntity entity = repository.save(new BookEntity(bookDTO.id(), bookDTO.title(), bookDTO.author()));
        return new BookDTO(entity.id(), entity.title(), entity.author());
    }

    public List<BookDTO> getAllBooks() {
        return repository.findAll().stream()
                .map(entity -> new BookDTO(entity.id(), entity.title(), entity.author()))
                .collect(Collectors.toList());
    }

    public BookDTO updateBook(Long id, BookDTO bookDTO) {
        BookEntity entity = repository.findById(id)
                .orElseThrow(() -> new RuntimeException("Book not found"));
        entity = new BookEntity(entity.id(), bookDTO.title(), bookDTO.author());
        repository.save(entity);
        return new BookDTO(entity.id(), entity.title(), entity.author());
    }

    public void deleteBook(Long id) {
        repository.deleteById(id);
    }
}

// Controller
@RestController
@RequestMapping("/books")
public class BookController {
    private final BookService service;

    @Autowired
    public BookController(BookService service) {
        this.service = service;
    }

    @PostMapping
    public ResponseEntity<BookDTO> createBook(@RequestBody BookDTO bookDTO) {
        BookDTO createdBook = service.createBook(bookDTO);
        return new ResponseEntity<>(createdBook, HttpStatus.CREATED);
    }

    @GetMapping
    public ResponseEntity<List<BookDTO>> getAllBooks() {
        List<BookDTO> books = service.getAllBooks();
        return new ResponseEntity<>(books, HttpStatus.OK);
    }

    @PutMapping("/{id}")
    public ResponseEntity<BookDTO> updateBook(@PathVariable Long id, @RequestBody BookDTO bookDTO) {
        BookDTO updatedBook = service.updateBook(id, bookDTO);
        return new ResponseEntity<>(updatedBook, HttpStatus.OK);
    }

    @DeleteMapping("/{id}")
    public void deleteBook(@PathVariable Long id) {
        service.deleteBook(id);
    }
}

// application.properties
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.jpa.hibernate.ddl-auto=update
spring.h2.console.enabled=true

Explanation:

1. BookEntity is a record used as a JPA entity with an auto-generated ID.

2. BookDTO is a Data Transfer Object, also a record, used for transferring data between the client and server.

3. BookRepository extends JpaRepository for CRUD operations on BookEntity.

4. BookService contains the business logic and interacts with BookRepository.

5. BookController manages HTTP requests and uses BookService for processing.

6. CRUD operations are demonstrated through various HTTP endpoints.

7. The application.properties file configures the H2 database and enables the H2 console for easy database access and management.

8. The example shows the full flow of CRUD operations in a Spring Boot application using Java Records and an H2 database, demonstrating a clean and efficient development approach.


Comments