Sub topic 4
Modeling the resource as a JPA entity
This chapter shows how to map the Book resource to a database table with JPA. It assumes you know Java classes, annotations, and basic SQL, and that the project from the earlier chapters already has spring-boot-starter-data-jpa and a configured database. The chapter covers the working model, the mapping annotations, how identifiers are generated, and the errors that most often appear at this step.
What an entity is
JPA (Jakarta Persistence API) is a specification for mapping Java objects to relational tables. Hibernate is the implementation that Spring Boot uses by default. An entity is a class that JPA manages. Each instance corresponds to one row, and each field corresponds to one column.
An entity is different from the DTOs you add in a later chapter. The entity describes how data is stored. A DTO describes what the API sends and receives. Keeping them apart lets you change the table without changing the JSON contract.
The Book entity
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
@Entity
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String title;
private String author;
protected Book() {
}
public Book(String title, String author) {
this.title = title;
this.author = author;
}
public Long getId() { return id; }
public String getTitle() { return title; }
public void setTitle(String title) { this.title = title; }
public String getAuthor() { return author; }
public void setAuthor(String author) { this.author = author; }
}Spring Boot 3 and later use the jakarta.persistence package. Older tutorials import javax.persistence, and those imports do not compile against Boot 3.
What each part does
@Entitytells Hibernate to manage the class. Without it, the class is an ordinary object and repositories cannot use it.@Idmarks the primary key. Every entity needs exactly one identifier (or a composite one, which this tutorial does not use).@GeneratedValuesays the database or Hibernate creates the key value, so your code never sets it.protected Book()is the no-argument constructor. Hibernate uses it to create instances when it reads rows. It can beprotected, so application code cannot create half-built books by accident.- The public constructor is the one your code calls. It takes the fields a new book needs and leaves
idempty. - Getters and setters give Hibernate and your code access to state. The entity has no setter for
id, because the key is assigned by the database.
By default, every non-static, non-transient field becomes a column. The class name becomes the table name, and Spring Boot's naming strategy converts camelCase to snakecase. Book maps to a table named book, and a field publishedYear would map to `publishedyear`.
How the identifier is generated
GenerationType controls where the key comes from. The choice affects performance and portability.
| Strategy | Source of the key | Notes |
|---|---|---|
| `IDENTITY` | An auto-increment column in the database | Simple. Hibernate must run the `INSERT` immediately to learn the key, which disables JDBC insert batching. |
| `SEQUENCE` | A database sequence | Allows batching. Not available in MySQL before 8.0 (MariaDB 10.3 added sequences). |
| `AUTO` | Hibernate picks based on the dialect | Behavior can differ between databases, so be explicit when it matters. |
| `UUID` | A generated UUID | Useful when clients or other systems must create keys. |
This tutorial uses IDENTITY because it works the same way on H2 and PostgreSQL and needs no extra setup. If you later insert thousands of rows at a time, move to SEQUENCE.
A new Book has id == null until it is saved. After repository.save(book) returns, the same object (for a new entity) holds the generated key. That is why the controller can read created.id() to build the Location header.
Entity lifecycle
An entity instance is always in one of four states relative to the persistence context. The persistence context is the set of entities Hibernate currently tracks within a transaction.
The diagram below shows those states.
- Transient: created with
new, not tracked, no id. - Managed: tracked by the persistence context. Hibernate compares its fields with a snapshot taken when it was loaded.
- Detached: was managed, but the transaction or session ended. Changes are no longer tracked.
- Removed: scheduled for deletion at commit.
Dirty checking is what makes the service's update method work. It loads a book, calls the setters, and never calls save. When the transaction commits, Hibernate sees that the managed entity differs from its snapshot and issues an UPDATE. The same code outside a transaction would change the object and write nothing.
Customizing the mapping
The defaults are enough for a first version, but real schemas need more control. These annotations are in jakarta.persistence.
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
@Entity
@Table(name = "books")
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false, length = 200)
private String title;
@Column(nullable = false, length = 100)
private String author;
protected Book() {
}
public Book(String title, String author) {
this.title = title;
this.author = author;
}
public Long getId() { return id; }
public String getTitle() { return title; }
public void setTitle(String title) { this.title = title; }
public String getAuthor() { return author; }
public void setAuthor(String author) { this.author = author; }
}@Table(name = "books")sets the table name. Use it when the table already exists under a different name.@Column(nullable = false, length = 200)describes the column. These settings only create constraints if Hibernate generates the schema. Withddl-auto=validate, the constraints come from your own SQL, and Hibernate only checks that the column exists with a compatible type.- Fields marked
@Transientare not stored.
A related gotcha: @Column(nullable = false) does not validate input. If a null title reaches the database, you get a constraint error at flush time. Request validation with @NotBlank (covered in a later chapter) rejects bad input earlier and produces a better error.
Where the schema comes from
The ddl-auto property from the database chapter decides whether Hibernate creates tables.
| Value | Behavior | Typical use |
|---|---|---|
| `none` | Hibernate does nothing | Production with a migration tool |
| `validate` | Checks that entities match the existing schema and fails at startup if they do not | Production |
| `update` | Adds missing tables and columns | Throwaway experiments only |
| `create-drop` | Builds the schema at startup and drops it at shutdown | Tests |
With an embedded H2 database and no explicit setting, Spring Boot defaults to create-drop, so the table appears automatically. With PostgreSQL and validate, the table must exist before the app starts. A minimal script for the first version of the table:
CREATE TABLE books (
id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
title VARCHAR(200) NOT NULL,
author VARCHAR(100) NOT NULL
);This script uses @Table(name = "books") from the customized mapping. If you keep the plain @Entity with no @Table, name the table book instead. Production projects usually keep such scripts under a migration tool like Flyway or Liquibase so schema changes are versioned.
Common errors and edge cases
Not a managed type: class ...Book. The class is missing@Entity, or it sits outside the packages scanned from your@SpringBootApplicationclass. Move it under the application's base package.No default constructor for entity. JPA needs a no-argument constructor. Addprotected Book() {}. A class with only the two-argument constructor fails at startup.Schema-validation: missing table [book]. Withvalidate, the name in the database does not match the mapping. Check@Table, or remember the snake_case conversion.- Table named
userororderfails. These are reserved words in SQL. Pick a different name, such asapp_user, or quote it explicitly. - Setting the id yourself. If you call
new Book(...)and later assign an id by reflection or a setter,savetreats the object as existing and may attempt an update that finds no row. Leave id generation to the database. - Using
finalfields or afinalclass. Hibernate creates proxies by subclassing and sets fields through reflection. Afinalclass prevents proxies for lazy loading, so avoid it on entities. - Records as entities. A record is immutable and has no no-argument constructor, so it cannot be an entity. Records fit the DTO layer instead.
Equality, briefly
Entities often end up in sets or get compared in tests. Do not use Lombok's @Data or generate equals from all fields, because mutable fields and a null id before saving make the result unstable. For a simple resource, leave equals and hashCode alone and compare ids in tests. If you need value equality later, base it on a stable business key, or use a well-known pattern that compares only non-null ids.
Checking the mapping
A repository test can confirm that the mapping works against H2. This test uses @DataJpaTest, which loads only JPA components.
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.data.jpa.repository.JpaRepository;
@DataJpaTest
class BookMappingTest {
@Autowired
private BookRepository repository;
@Test
void savingAssignsAnId() {
Book saved = repository.saveAndFlush(new Book("Dune", "Frank Herbert"));
assertThat(saved.getId()).isNotNull();
assertThat(repository.findById(saved.getId()))
.get()
.extracting(Book::getTitle)
.isEqualTo("Dune");
}
}saveAndFlush forces the INSERT to run now, so a mapping problem surfaces inside the test. @DataJpaTest replaces your datasource with an embedded database and rolls back each test.
Exercise
A developer's update service method loads a Book, calls setTitle, and returns, but the title never changes in the database. The method has no @Transactional annotation and the entity is loaded through findById. What is wrong, and how do you fix it?
Show answer
Without a transaction on the service method, the entity is detached as soon as findById returns, because the repository call finishes its own short transaction. Hibernate no longer tracks the object, so dirty checking never runs and no UPDATE is issued. Fix it by annotating the method with @Transactional, so the entity stays managed until commit, or by calling repository.save(book) explicitly.
Exercise
Why does IDENTITY generation disable JDBC insert batching, and which strategy would you move to for bulk inserts?
Show answer
With IDENTITY, the database assigns the key during the INSERT, so Hibernate must run each insert immediately to learn the id and cannot group several inserts into one batch. A SEQUENCE strategy lets Hibernate fetch keys ahead of time, so it can delay and batch the inserts. Use SEQUENCE for bulk inserts.