JPA Entities and Repositories
Explore how to create and manage JPA entities using annotations like @Entity and @Id, and understand how JpaRepository supports CRUD and batch operations. This lesson guides you through setting up entity mappings, repository interfaces, and performing data operations within a Spring Data JPA application.
In Spring Data JPA, entities represent the persistent data model, typically annotated with JPA annotations for mapping to database tables. Repositories provide a convenient way to interact with the database, offering predefined methods for CRUD operations and custom query creation.
Entity
In this lesson, we’ll use the same example of the Book and Author POJO referencing the book and author database tables and convert them into JPA entities.
Create a Book entity
Let’s learn a few handy annotations to transform a POJO into an entity.
The most common annotations are @Entity and @Id.
-
The
@Entityannotation allows mapping a POJO to a database table with the underlying data access layer. -
The
@Idannotation allows mapping property to a primary key in the database table.
We use these annotations to convert the Book POJO from the com.smartdiscover.entity package to an entity and map it to the Book table.
Explanation:
-
Lines 13 and 14: The
longtype propertyidis a unique identifier for which we want to automatically generate the value when an instance persists in the database. So, we use the@GeneratedValueannotation to define theAUTOvalue for theGenerationType, allowing the JPA to choose the appropriate strategy forid...