Sub topic 1
Spring Data JPA Entities and Repositories
Prerequisites
Assume you know core Java, basic SQL, relational tables, and Spring Boot dependency injection. You should understand primary keys, foreign keys, and joins.
What JPA, Hibernate, and Spring Data JPA Do
JPA (Jakarta Persistence API) is a specification. It defines annotations and rules for mapping Java objects to relational tables. Hibernate is a popular JPA implementation. It generates SQL and manages database operations.
Spring Data JPA adds repository interfaces and query generation. You describe an interface, and Spring creates its implementation at startup.
| Layer | Main responsibility |
|---|---|
| JPA | Defines object-relational mapping rules |
| Hibernate | Implements those rules and executes SQL |
| Spring Data JPA | Creates repositories and query methods |
Setting Up Spring Data JPA in Spring Boot
Add spring-boot-starter-data-jpa and your database driver to the project. Spring Boot then configures an EntityManager, which tracks persistent entities.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>For development with PostgreSQL, configure the connection in application.properties:
spring.datasource.url=jdbc:postgresql://localhost:5432/library
spring.datasource.username=library_app
spring.datasource.password=${DB_PASSWORD}
spring.jpa.hibernate.ddl-auto=validatevalidate checks that the schema matches the mappings. Use migrations such as Flyway or Liquibase to create production schemas.
Mapping a Class to a Table
@Entity marks a class as persistent. @Table chooses its table name. An entity must have an identifier marked with @Id.
import jakarta.persistence.*;
@Entity
@Table(name = "books")
class Book {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false)
private String title;
protected Book() { } // Required by JPA
Book(String title) {
this.title = title;
}
}Identifiers and Value Types
IDENTITY lets the database generate an identifier, often with an identity column. SEQUENCE uses a database sequence and can be more efficient for batches. Choose a strategy supported by your database and migration setup.
An @Embeddable value has no independent identity. An enum can be stored safely as text with EnumType.STRING.
@Embeddable
class Address {
private String city;
private String country;
}
@Enumerated(EnumType.STRING)
private BookStatus status;Modeling Associations and the Owning Side
In a one-to-many relationship, the @ManyToOne side usually owns the foreign key. The mappedBy side is inverse and does not create a second foreign key.
flowchart LR
A[Author] -->|one author_id| B[Book]Exercise
Which side normally owns the foreign key in an Author-to-Book one-to-many association?
Show answer
The Book entity's @ManyToOne association normally owns the author_id foreign key.