...

/

JPA Entities and Repositories

JPA Entities and Repositories

Explore entities and repositories through the Spring Data JPA framework.

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 @Entity annotation allows mapping a POJO to a database table with the underlying data access layer.

  • The @Id annotation 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.

Press + to interact
package com.smartdiscover.entity;
import jakarta.persistence.*;
import lombok.Data;
import java.util.List;
import java.util.stream.Collectors;
@Data
@Entity
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
private String summary;
@ManyToMany
@JoinTable(
name = "book_authors",
joinColumns = @JoinColumn(name = "book_id"),
inverseJoinColumns = @JoinColumn(name = "author_id"))
private List<Author> authors;
@Override
public String toString() {
return "Book{" +
"id=" + id +
", name='" + name + '\'' +
", summary='" + summary + '\'' +
", authors='" + authors.stream().map(i-> i.getFullName()).collect(Collectors.toList()) + '\'' +
'}';
}
}

Explanation:

  • Lines 13 and 14: The long type property id is a unique identifier for which we want to automatically generate the value when an instance persists in the database. So, we use the @GeneratedValue annotation to define the AUTO value for the ...