Integration of POJO with the JDBC Repository
Learn how to integrate a POJO with the JDBC repository for database access.
Integrating a POJO class with a JDBC repository involves mapping the class fields to database columns and implementing CRUD operations. This enables seamless data persistence, retrieval, and manipulation by leveraging JDBC APIs to interact with the underlying database for efficient and reliable data storage.
POJOs
First, we create the Book
and Author
POJO classes referencing the book
and author
database tables. Let’s visualize a class diagram for our POJOs.
Here, we’ve taken a practical scenario where one book can have one or more authors, and one author can write one or more books. So, we have a many-to-many mapping between the Book
and Author
objects.
The Book
POJO
First, let’s create the Book
POJO class in the com.smartdiscover.entity
package.
package com.smartdiscover.entity;import lombok.Data;import org.springframework.data.annotation.*;import org.springframework.data.relational.core.mapping.MappedCollection;import org.springframework.data.relational.core.mapping.Table;import java.util.Date;import java.util.HashSet;import java.util.Set;@Data@Table(name = "BOOK")public class Book {@Idprivate long id;private String name;private String summary;@MappedCollection(idColumn = "BOOK_ID")private Set<AuthorBook> authors = new HashSet<>();@Overridepublic String toString() {return "Book{" +"id=" + id +", name='" + name + '\'' +", summary='" + summary + '\'' +", authors=" + authors.stream().mapToLong(i -> i.getAuthorId()).boxed().toList().toString() +'}';}}
Explanation:
- Line 12: We use Lombok’s
@Data
annotation to generate the getters and setters of the properties. - Line 13: We add the
@Table
annotation to connect