TExcelTAD
Home › Spring Boot › Entities & Repositories

Entities & Repositories

An entity is a Java class whose instances are rows in a table. JPA annotations describe the mapping — table and column names, keys, constraints, enums, timestamps. A repository loads and saves entities. This lesson builds the Task entity used throughout the rest of the course and wires it into a service.

Mapping a class to a table

java
package com.example.tasks.task;

import jakarta.persistence.*;
import java.time.Instant;
import java.time.LocalDate;

@Entity
@Table(name = "tasks")
public class Task {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false, length = 120)
    private String title;

    @Column(length = 2000)
    private String description;

    @Enumerated(EnumType.STRING)          // store "HIGH", not 2
    @Column(nullable = false, length = 10)
    private Priority priority = Priority.MEDIUM;

    private boolean done;

    private LocalDate dueDate;

    @Column(name = "created_at", nullable = false, updatable = false)
    private Instant createdAt;

    @Version                               // optimistic locking
    private long version;

    protected Task() {}                    // for JPA only

    public Task(String title, Priority priority) {
        this.title = title;
        this.priority = priority;
    }

    @PrePersist
    void onCreate() { createdAt = Instant.now(); }

    // getters, plus intention-revealing methods instead of blind setters
    public void complete() { this.done = true; }
    public void rename(String newTitle) { this.title = newTitle; }
    ...
}
bash · try it yourself
./mvnw -q spring-boot:run | grep "create table"
Hibernate: create table tasks (done boolean not null, due_date date, created_at timestamp(6) with time zone not null, id bigint generated by default as identity, version bigint not null, priority varchar(10) not null check ((priority in ('LOW','MEDIUM','HIGH'))), title varchar(120) not null, description varchar(2000), primary key (id))

Hibernate turns camelCase fields into snake_case columns (dueDate → due_date) by default in Spring Boot.

Mapping rules to know

Annotation Purpose
@Entity the class is persistent; needs a no-arg constructor (may be protected)
@Table(name = …) table name (default: derived from the class name)
@Id primary key
@GeneratedValue key generated by the DB (IDENTITY) or a sequence (SEQUENCE)
@Column name, nullable, length, unique, updatable
@Enumerated(EnumType.STRING) store enum names; never use the default ORDINAL
@Version optimistic locking counter
@Transient field not persisted
@PrePersist / @PreUpdate lifecycle callbacks

Note: JPA entities should not be records: JPA needs a no-arg constructor, mutable state and proxies for lazy loading. Use records for DTOs and projections, classes for entities.

Why EnumType.STRING matters

ORDINAL stores the enum's position. Insert a new constant in the middle and every existing row silently changes meaning:

java · try it yourself
import java.util.List;

class Main {
    enum PriorityV1 { LOW, MEDIUM, HIGH }
    enum PriorityV2 { LOW, NORMAL, MEDIUM, HIGH }      // NORMAL added later

    public static void main(String[] args) {
        List<PriorityV1> saved = List.of(PriorityV1.LOW, PriorityV1.MEDIUM, PriorityV1.HIGH);
        System.out.println("stored value -> read back with V2");
        for (PriorityV1 p : saved) {
            int ordinal = p.ordinal();
            String name = p.name();
            System.out.printf("ORDINAL %d -> %-6s | STRING %-6s -> %s%n",
                    ordinal, PriorityV2.values()[ordinal], name, PriorityV2.valueOf(name));
        }
    }
}
stored value -> read back with V2
ORDINAL 0 -> LOW    | STRING LOW    -> LOW
ORDINAL 1 -> NORMAL | STRING MEDIUM -> MEDIUM
ORDINAL 2 -> MEDIUM | STRING HIGH   -> HIGH

With ORDINAL, every MEDIUM task became NORMAL and every HIGH one MEDIUM. With STRING nothing changed.

The repository

java
public interface TaskRepository extends JpaRepository<Task, Long> {
    List<Task> findByDoneFalseOrderByDueDateAsc();
    boolean existsByTitleIgnoreCase(String title);
}

Using it from a service

java
@Service
@Transactional
public class TaskService {
    private final TaskRepository tasks;
    public TaskService(TaskRepository tasks) { this.tasks = tasks; }

    public Task create(CreateTaskRequest req) {
        if (tasks.existsByTitleIgnoreCase(req.title())) throw new DuplicateTitleException(req.title());
        return tasks.save(new Task(req.title(), req.priority()));
    }

    public Task complete(long id) {
        Task task = tasks.findById(id).orElseThrow(() -> new TaskNotFoundException(id));
        task.complete();          // no save() needed: dirty checking (see below)
        return task;
    }

    @Transactional(readOnly = true)
    public List<Task> open() { return tasks.findByDoneFalseOrderByDueDateAsc(); }
}
bash · try it yourself
curl -s -X POST localhost:8080/api/tasks/1/complete
{"id":1,"title":"Learn JPA","description":null,"priority":"MEDIUM","done":true,"dueDate":null}
text
Hibernate: select t1_0.id,t1_0.created_at,t1_0.description,t1_0.done,t1_0.due_date,t1_0.priority,t1_0.title,t1_0.version from tasks t1_0 where t1_0.id=?
Hibernate: update tasks set created_at=?,description=?,done=?,due_date=?,priority=?,title=?,version=? where id=? and version=?

Dirty checking

Inside a transaction, a loaded entity is managed. Hibernate keeps a snapshot of its state and, at commit, compares the snapshot with the current values; changed entities are written with an UPDATE. That is why complete() needs no save() call. Here is the mechanism in miniature:

java · try it yourself
import java.util.*;

class Task {
    final long id;
    String title;
    boolean done;
    Task(long id, String title, boolean done) { this.id = id; this.title = title; this.done = done; }
    List<Object> state() { return List.of(title, done); }
}

class PersistenceContext {
    private final Map<Long, Task> managed = new LinkedHashMap<>();
    private final Map<Long, List<Object>> snapshots = new HashMap<>();

    Task find(long id, Map<Long, Task> db) {
        Task t = db.get(id);
        managed.put(id, t);
        snapshots.put(id, t.state());     // remember what we loaded
        return t;
    }

    void flush() {
        for (Task t : managed.values()) {
            if (!t.state().equals(snapshots.get(t.id))) {
                System.out.println("UPDATE tasks SET title='" + t.title + "', done=" + t.done + " WHERE id=" + t.id);
                snapshots.put(t.id, t.state());
            } else {
                System.out.println("(task " + t.id + " unchanged, no SQL)");
            }
        }
    }
}

class Main {
    public static void main(String[] args) {
        Map<Long, Task> db = Map.of(1L, new Task(1, "Learn JPA", false), 2L, new Task(2, "Deploy", false));
        PersistenceContext pc = new PersistenceContext();
        Task first = pc.find(1, db);
        pc.find(2, db);
        first.done = true;                // just change the object
        System.out.println("commit:");
        pc.flush();
    }
}
commit:
UPDATE tasks SET title='Learn JPA', done=true WHERE id=1
(task 2 unchanged, no SQL)

Tip: Don't generate setters for every field. Methods like complete() and rename() keep business rules inside the entity and make the code read like the domain.

Test yourself

Why should enums be mapped with @Enumerated(EnumType.STRING)?

  1. It is faster
  2. Reordering or inserting constants would otherwise change the meaning of stored ordinals
  3. ORDINAL is not supported by Hibernate
  4. STRING uses less storage

Inside a transaction you load a Task and call task.complete(). What else is needed to persist the change?

  1. Call repository.save(task)
  2. Call entityManager.flush() manually
  3. Nothing: dirty checking writes the update at commit
  4. Reload the entity

Why are Java records unsuitable as JPA entities?

  1. Records cannot have annotations
  2. JPA requires a no-arg constructor and mutable, proxyable classes
  3. Records cannot have a Long field
  4. Records are not serialisable