Skip to content
notes.vinhnq.com

Search

Database & ORMJunior23 min read

ORM and JPA: JDBC, Hibernate, entities and repositories

Review 21 cards
On this page

ORM and JPA series: 1. Entities and repositories · 2. Entity relationships · 3. The E-Learning schema, DTOs, JSON · 4. Persistence context and N+1 · 5. JPQL, @Transactional, locking

Typing repository.save(entity) is easy; using it correctly in production means understanding the layers underneath: JDBC, the connection pool, JPA, Hibernate and Spring Data. After this post you can define entities, repositories and services, and avoid three real sources of incidents: a drained pool, a schema managed by ddl-auto, and broken equals/hashCode. You only need basic Java and SQL (see the Databases series); relationships are in part 2, JPQL, @Transactional and locking in part 5.

1. The problem: why we need a database

Key idea: data kept in an ArrayList disappears on restart, is capped by RAM and can’t be shared between instances. A database fixes all three, and adds safe concurrent access and flexible queries.

Take a hotel (or course) app that keeps rooms, staff and guests in ArrayLists:

  • Data is lost on a crash or restart, because RAM is volatile.
  • Capacity is limited: RAM is far smaller and pricier than disk.
  • It doesn’t scale: two instances behind a load balancer each hold their own, diverging copy.
  • Missing: safe concurrent access (transactions, locks) and flexible querying (filters, joins, aggregates).
flowchart LR
  A[Spring Boot app] --> R[Repository / JPA]
  R --> H[Hibernate]
  H --> J[JDBC API]
  J --> D[Database driver<br/>mysql-connector-j]
  D -->|MySQL wire protocol| DB[(MySQL)]

2. Terminology

Key idea: the driver talks to the database, JDBC is the standard interface on top of drivers, an ORM converts objects ↔ rows, JPA is Java’s ORM specification, and Hibernate implements JPA.

2.1. Database driver and JDBC

Key idea: the driver handles each database’s own wire protocol; JDBC is the standard set of interfaces every driver implements, so the code above it stays database-agnostic.

  • The driver handles: the protocol, security (authentication, TLS), errors (error codes, dropped connections), performance (prepared statements, compression, batching).
  • JDBC: Connection, PreparedStatement, ResultSet. Each database ships its own driver (mysql-connector-j, postgresql).
  • A connection pool (the slides skip it, production always has one; Spring Boot defaults to HikariCP): a TCP connect plus authentication costs milliseconds to tens of milliseconds, so the pool keeps connections ready for reuse. Too small and requests queue; too large and the database drowns.

Plain JDBC means writing SQL, mapping the ResultSet and managing connections by hand, hundreds of times over. That’s why ORMs exist:

String sql = "SELECT id, title, price FROM courses WHERE teacher_id = ?";
try (Connection conn = dataSource.getConnection();
     PreparedStatement ps = conn.prepareStatement(sql)) {
    ps.setLong(1, teacherId);
    try (ResultSet rs = ps.executeQuery()) {
        List<Course> result = new ArrayList<>();
        while (rs.next()) {
            result.add(new Course(rs.getLong("id"), rs.getString("title"), rs.getBigDecimal("price")));
        }
        return result;
    }
}

2.2. ORM

Key idea: ORM (Object-Relational Mapping) automatically converts between Java objects and table rows, in both directions. It exists because the two models don’t line up (the object-relational impedance mismatch).

Java Relational
Objects have identity (==) and equality (equals) Rows are identified by a primary key
A reference course.getTeacher() A foreign key teacher_id + a JOIN
A collection teacher.getCourses() Doesn’t exist; you query back through the FK
Inheritance No such concept
Free navigation of an object graph Every “hop” is a query

2.3. JPA and Hibernate

Key idea: JPA is a specification (interfaces + annotations) and runs nothing by itself. Hibernate is the implementation Spring Boot uses by default. Spring Data JPA sits on top and generates repositories from interfaces.

  • JPA (Java Persistence API, now Jakarta Persistence): EntityManager, @Entity, @OneToMany… describe how objects map to tables and how to work with them.
  • Hibernate: the most popular implementation. Others: EclipseLink, OpenJPA.
  • Spring Data JPA: generates repositories, derives queries from method names, handles pagination.
flowchart TB
  SD[Spring Data JPA<br/>JpaRepository, derived queries] --> JPA[JPA spec<br/>EntityManager, annotations]
  JPA --> HB[Hibernate<br/>implementation]
  HB --> JDBC[JDBC + driver]

Since Spring Boot 3 the package is jakarta.persistence.*; old code using javax.persistence.* won’t compile on Boot 3+.

What JPA/Hibernate gives you:

  • ORM: entity-to-table mapping.
  • JPQL: queries over entities that Hibernate translates to your database’s SQL (more in part 5 of the series).
  • Schema generation (spring.jpa.hibernate.ddl-auto): handy while learning, never update/create in production (see section 3.7).
  • Performance features: the first-level cache (the persistence context — the set of entities Hibernate keeps loaded within one transaction), the second-level cache, lazy loading, batching, dirty checking (detecting changed fields to generate UPDATEs).
  • Spring integration: declarative transactions, repositories, exception translation.

3. Getting started

Key idea: you need two dependencies, an entity, a repository interface and a service with @Transactional. The mistakes hide in the details: id strategy, pool size, schema management, equals/hashCode.

3.1. Setup

Key idea: add the Spring Data JPA starter and the MySQL driver, declare the datasource in application.yml; Spring Boot infers the driver class and (since Hibernate 6) the dialect.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
    <groupId>com.mysql</groupId>
    <artifactId>mysql-connector-j</artifactId>
    <scope>runtime</scope>
</dependency>
spring:
  datasource:
    url: jdbc:mysql://localhost:3306/elearning
    username: app
    password: ${DB_PASSWORD}        # from an environment variable; never commit passwords
    hikari:
      maximum-pool-size: 10
  jpa:
    hibernate:
      ddl-auto: validate            # update is fine in dev; validate + Flyway in prod
    open-in-view: false             # see part 5 of the series
    properties:
      hibernate:
        jdbc.batch_size: 50
        default_batch_fetch_size: 50
logging:
  level:
    org.hibernate.SQL: debug        # print SQL during development

You usually don’t need driver-class-name: Spring Boot infers it from the URL.

3.2. Defining an entity

Key idea: an entity is a class with @Entity, @Id and a no-arg constructor. The three choices that matter most: the id strategy, enums stored as STRING, and no Lombok @Data.

import jakarta.persistence.*;

@Entity
@Table(name = "courses")
public class Course {

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

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

    @Column(precision = 12, scale = 2)
    private BigDecimal price;

    @Enumerated(EnumType.STRING)
    private CourseStatus status;

    @Transient
    private int viewCountInMemory; // not persisted

    protected Course() {} // required by JPA

    public Course(String title, BigDecimal price) {
        this.title = title;
        this.price = price;
        this.status = CourseStatus.DRAFT;
    }
    // getters, domain methods...
}
Annotation / rule Meaning
@Entity A JPA-managed class
@Id The primary key, mandatory
@Table The table name; without it Spring Boot turns CourseCategory into course_category
@Transient A field that isn’t persisted
No-arg constructor Hibernate instantiates via reflection when reading from the database. protected is enough and better than public, because other code can’t create half-empty objects
No final (class or methods) Hibernate creates proxies (subclasses) for lazy loading

3.3. Defining a repository

Key idea: declare an interface extending JpaRepository<Entity, IdType>; Spring Data generates the implementation at startup and derives queries from method names (derived queries).

public interface CourseRepository extends JpaRepository<Course, Long> {

    List<Course> findByStatus(CourseStatus status);

    Optional<Course> findByTitleIgnoreCase(String title);

    Page<Course> findByTeacherId(Long teacherId, Pageable pageable);

    boolean existsByTitle(String title);
}
  • The implementation is a proxy backed by SimpleJpaRepository, with save, findById, findAll, deleteById, paging and sorting out of the box.
  • Derived queries: Spring Data parses names such as findByStatus into JPQL.
  • The slides say to add @Repository; for an interface extending JpaRepository that’s unnecessary (Spring Data detects it, exception translation is already in place). @Repository is for hand-written DAO classes.
  • save() calls persist when the entity counts as new (usually a null id), otherwise merge, which copies its whole state onto the database row. Bind a form straight to the entity and call save(), and every column not on the form becomes null: see the form binding and validation post.

3.4. Defining a service

Key idea: the service holds business logic and the transaction boundary (@Transactional), and receives its dependencies through the constructor.

@Service
public class CourseService {

    private final CourseRepository courseRepository;

    public CourseService(CourseRepository courseRepository) { // constructor injection
        this.courseRepository = courseRepository;
    }

    @Transactional
    public CourseResponse create(CreateCourseRequest req) {
        if (courseRepository.existsByTitle(req.title())) {
            throw new DuplicateCourseException(req.title());
        }
        Course saved = courseRepository.save(new Course(req.title(), req.price()));
        return CourseResponse.from(saved);
    }

    @Transactional(readOnly = true)
    public CourseResponse get(long id) {
        return courseRepository.findById(id)
                .map(CourseResponse::from)
                .orElseThrow(() -> new CourseNotFoundException(id));
    }
}

The slides use @Autowired on a field; prefer constructor injection: fields can be final, there’s no “not yet injected” state, tests don’t need Spring, and a class with too many dependencies shows it right in the constructor. With a single constructor you don’t need @Autowired. More in IoC and Dependency Injection.

3.5. The layers: Controller, DTO, Service, Repository, Entity

Key idea: DTOs travel between Client, Controller and Service; entities travel between Service, Repository and the database. The service is the only place that sees both, so map entities to DTOs there, while the transaction is still open.

Component Its job Works with
Controller Receives HTTP requests, maps endpoints (@GetMapping…), validates input, calls the service, returns the response. No business logic. DTOs
DTO (Data Transfer Object) Carries data between client and server, and between controller and service. Holds only the fields the use case needs, so the entity’s sensitive fields stay hidden (passwords, internal states). Controller, Service
Service Business logic, transaction boundaries, calls repositories, converts entity ↔ DTO. DTOs above, entities below
Repository Queries and changes data. Entities
Entity A class mapped to a table. Repository, ORM
flowchart LR
  C[Client] <-->|JSON = DTO| CT[Controller]
  CT <-->|DTO| SV[Service]
  SV <-->|Entity| RP[Repository]
  RP <-->|"Entity ↔ SQL (Hibernate)"| DB[(Database)]
public record CourseResponse(Long id, String title, String teacherName) {
    static CourseResponse from(Course c) {
        return new CourseResponse(c.getId(), c.getTitle(), c.getTeacher().getName());
    }
}

@Transactional(readOnly = true)
public CourseResponse get(long id) {                       // in CourseService
    return courseRepository.findById(id)
            .map(CourseResponse::from)                      // touches LAZY associations while the session is open
            .orElseThrow(() -> new CourseNotFoundException(id));
}

Why not return entities directly (leaked password, JSON recursion on bidirectional relationships, LAZY proxy errors) is shown with real runs in part 3 of the series. The package layout of a complete project is in Designing REST APIs with Spring Boot (section 4.1).

3.6. The connection pool: configuring HikariCP

Key idea: Spring holds a connection for the whole transaction, not just while SQL runs. So short transactions matter more than a big pool, and a big pool doesn’t make the database faster.

  • Spring borrows a connection when a transaction starts (or when a repository queries outside one) and returns it when the transaction ends.
  • A database only truly runs about as many things in parallel as it has CPU cores (plus slack for disk waits); beyond that, connections just fight over CPU, locks and memory.
  • The pool size budget is for the whole system, divided by the number of application instances.
HikariCP settings, the sizing formula and the metrics to watch
Setting (spring.datasource.hikari.*) Default Meaning
maximum-pool-size 10 Maximum number of connections, idle ones included
minimum-idle same as maximum-pool-size HikariCP recommends leaving it: a fixed-size pool
connection-timeout 30000 ms Wait longer than this for a connection and you get SQLTransientConnectionException
max-lifetime 1800000 ms (30 min) Retire and replace old connections; keep it a few minutes below any DB or proxy/firewall timeout

HikariCP’s starting formula: connections = core_count * 2 + effective_spindle_count. An 8-core database on SSDs wants roughly 16-20 connections for the whole system. 10 pods with a pool of 20 each is 200 connections to one database, more than MySQL’s default max_connections of 151.

Before raising the pool size, look at hikaricp.connections.pending and hikaricp.connections.acquire (Micrometer via Actuator) to see whether requests are actually waiting for connections.

3.7. Managing the schema: Flyway instead of ddl-auto

Key idea: production uses versioned migrations (Flyway/Liquibase): every schema change is a numbered SQL file, reviewed like code, applied exactly once per environment. Hibernate is set to ddl-auto=validate.

  • ddl-auto takes none, validate, update, create, create-drop. Spring Boot defaults to create-drop for embedded databases (H2) when there’s no Flyway/Liquibase, and to none for real databases.
  • Flyway records the history in a flyway_schema_history table, with a checksum (a fingerprint of the content) of each file.
  • Add org.flywaydb:flyway-core (plus flyway-mysql for MySQL); Spring Boot runs the migrations at startup, before Hibernate validates.
src/main/resources/db/migration/
  V1__create_courses.sql
  V2__add_course_status.sql
-- V2__add_course_status.sql
ALTER TABLE courses ADD COLUMN status VARCHAR(20) NOT NULL DEFAULT 'DRAFT';
CREATE INDEX idx_courses_status ON courses (status);

3.8. equals and hashCode on entities

Key idea: entities often live in Sets, so equals/hashCode must hold in every state: before persist (null id), after persist, and as a proxy. Use an immutable natural key if there is one; with only a generated id, equals by id and a constant hashCode.

@Entity
public class Course {
    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    // ...

    public Long getId() { return id; }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Course other)) return false; // a proxy is a subclass, so instanceof still matches
        return id != null && id.equals(other.getId());  // go through the getter, never other.id
    }

    @Override
    public int hashCode() {
        return Course.class.hashCode(); // constant: same before and after persist, same for proxies
    }
}
  • Two transient entities (null ids) are equal only if they’re the same object.
  • An immutable natural key (ISBN, a business-assigned course code, an email that can’t change) beats the approach above; base both equals and hashCode on it.
Why a constant hashCode is acceptable, and the proxy trap in equals

A constant hashCode means the object never lands in the “wrong” bucket once its id is assigned. The cost is that every entity of the class shares one bucket, so a huge HashSet degrades to a linear scan; acceptable because in-memory entity collections are usually small. Use Course.class.hashCode() rather than getClass().hashCode(), because a proxy’s class differs from the entity class.

Exercises

All exercises across the three ORM lessons build on the e-learning pet project (another edition of the course uses a hotel management brief with Hotel, Room and Employee; the approach is identical). The full brief is in Hands-on pet project.

Exercise 1: Create an entity for every table

Task (paraphrased): for each table in the pet project’s database design, create a matching entity.

Solution to Exercise 1: the entity list and the Teacher entity

Following the course’s E-Learning schema (rebuilt in full in part 3 of the series), create User, FullName, Admin, Teacher, Course, Chapter, Lesson, UserCourse, UserCourseLesson and Address.

  • Each has @Id + @GeneratedValue (except UserCourse, which uses an @EmbeddedId composite key) and a protected no-arg constructor.
  • Status and lesson-type columns are enums stored with EnumType.STRING.
  • No column named order, since it clashes with an SQL keyword.
  • Relationships aren’t needed yet (that’s Exercise 4). Here is Teacher, a table with no foreign keys:
@Entity
@Table(name = "teacher")
public class Teacher {
    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false, unique = true)
    private String username;

    @Column(nullable = false)
    private String password;            // a hash, never the raw password

    @Enumerated(EnumType.STRING)
    @Column(nullable = false, length = 50)
    private Status status = Status.ACTIVE;

    @CreationTimestamp
    @Column(name = "created_date", updatable = false)
    private Instant createdDate;

    @UpdateTimestamp
    @Column(name = "updated_date")
    private Instant updatedDate;

    protected Teacher() {}

    public Teacher(String username, String passwordHash) {
        this.username = username;
        this.password = passwordHash;
    }
}

Verification: set ddl-auto=validate and let Flyway create the tables; if an entity drifts from the schema, the app refuses to start, so you find out during development rather than at runtime.

Exercise 2: A repository per entity

Task (paraphrased): create a repository interface for each entity.

public interface TeacherRepository extends JpaRepository<Teacher, Long> {}
public interface UserRepository extends JpaRepository<User, Long> {
    Optional<User> findByUsername(String username);
    boolean existsByUsername(String username);
}
public interface UserCourseRepository extends JpaRepository<UserCourse, UserCourseId> {
    long countByCourseId(Long courseId);
}

Not every entity needs its own repository: a child that only lives inside an aggregate (like FullName, cascaded from User) is handled through its parent. That’s DDD’s aggregate root idea.

Exercise 3: Replace the echo endpoints with real data (CRUD)

Task (paraphrased): the endpoints defined in the REST lesson (which currently echo their input) must now read and write the real database. The other edition of the course asks for the same thing: full CRUD for each main entity (hotels, rooms, staff…).

Solution to Exercise 3: a CRUD CourseService
@Service
public class CourseService {
    private final CourseRepository courseRepository;
    private final TeacherRepository teacherRepository;

    public CourseService(CourseRepository courseRepository, TeacherRepository teacherRepository) {
        this.courseRepository = courseRepository;
        this.teacherRepository = teacherRepository;
    }

    @Transactional
    public CourseResponse create(CourseRequest req) {
        // getReferenceById returns a proxy without a SELECT; we only need the id for the FK.
        // If the teacher doesn't exist, the FK constraint fails on INSERT.
        Teacher teacher = teacherRepository.getReferenceById(req.teacherId());
        Course course = new Course(req.name(), req.description());
        teacher.addCourse(course);
        return CourseResponse.from(courseRepository.save(course));
    }

    @Transactional(readOnly = true)
    public Page<CourseResponse> search(Pageable pageable) {
        return courseRepository.findAll(pageable).map(CourseResponse::from);
    }

    @Transactional
    public CourseResponse update(long id, CourseRequest req) {
        Course course = courseRepository.findById(id)
                .orElseThrow(() -> new CourseNotFoundException(id));
        course.update(req.name(), req.description()); // dirty checking issues the UPDATE
        return CourseResponse.from(course);
    }

    @Transactional
    public void delete(long id) {
        if (!courseRepository.existsById(id)) throw new CourseNotFoundException(id);
        courseRepository.deleteById(id);
    }
}

Points worth noticing:

  • update doesn’t call save (dirty checking).
  • create uses getReferenceById to skip a SELECT.
  • search is paginated from day one.
  • A missing course throws an exception that a @RestControllerAdvice turns into a 404.
  • If CourseResponse.from reads course.getTeacher().getName() inside search, you get N+1, so enable default_batch_fetch_size or use a projection (see part 4 of the series).

Remember

  • Explain which layer JPA, Hibernate and Spring Data JPA each sit at.
  • Know why IDENTITY loses batch inserts, and when to pick SEQUENCE or UUID v7.
  • Explain why a bigger pool doesn’t speed up the database, and why an HTTP call inside @Transactional drains the pool.
  • Know why production uses Flyway + validate, and what happens when you edit an applied migration.
  • Write a safe equals/hashCode for an entity that only has a generated id.

Interview questions

Junior

What’s the difference between JPA and Hibernate?

JPA is a specification; Hibernate is one implementation of it.

JPA (Jakarta Persistence) is a set of interfaces and annotations that define how objects map to tables. Hibernate implements it and adds features of its own. Code written against the JPA API can switch to another implementation such as EclipseLink. Spring Data JPA sits on top and generates repositories.

Why does an entity need a no-arg constructor?

Because Hibernate creates the object via reflection when reading from the database, then sets its fields.

The constructor can be protected so outside code can’t create empty objects. Hibernate also creates proxies (subclasses) for lazy loading, so the class must not be final.

Why shouldn’t you use ddl-auto=update in production?

Because it never drops or renames columns, doesn’t migrate data, keeps no history and can’t be reviewed.

Renaming a field just adds a new column and leaves the data in the old one; environments can drift apart. Production uses versioned migrations (Flyway, Liquibase) applied at deploy time, with Hibernate set to ddl-auto=validate so it only checks that the entities match the schema.

Mid

What is a derived query? When do you switch to @Query?

A derived query is one Spring Data generates from the method name; switch to @Query when the name gets too long or needs something a name can’t express.

Spring Data parses a name such as findByStatusAndTeacherId into JPQL at startup (a wrong field name stops the app from booting, so errors surface early). It’s great for one or two conditions. Switch to @Query for joins or fetch joins, DTO projections, bulk updates/deletes, or database-specific features (native queries). For dynamic filters, use Specifications or Querydsl.

How do findById and getReferenceById differ?

findById SELECTs right away and returns an Optional; getReferenceById returns a proxy holding only the id, with no query.

findById (or the persistence context) tells you for sure the row exists. Use getReferenceById when you only need to set a foreign key and want to save a SELECT. If the id doesn’t exist, the error only shows up when you touch a proxy field (EntityNotFoundException) or when the INSERT violates the FK.

What is a connection pool? How many requests can a pool of 10 serve?

A pool keeps opened connections for reuse; how many requests it serves depends on how long each transaction holds a connection, not just on the number 10.

The pool avoids a TCP connect plus login per request. At most 10 transactions hold a connection at once; everyone else waits up to connection-timeout. By Little’s law, if a transaction holds one for 20 ms, 10 connections serve about 500 transactions per second. That’s why keeping transactions short matters more than growing the pool, and an oversized pool overloads the database.

Senior

Why does GenerationType.IDENTITY disable batch inserts? Which id strategy would you pick?

Because the id only exists after the INSERT runs, and Hibernate needs it as soon as you persist, so it inserts one row at a time.

Hibernate needs the id to put the entity in the persistence context. SEQUENCE with a pooled optimizer pre-allocates ids, so inserts batch nicely; that’s the best choice on PostgreSQL/Oracle. On MySQL you usually live with IDENTITY, or generate time-ordered ids in the application (UUID v7, Snowflake) to avoid index fragmentation, plus Persistable so save doesn’t issue a needless SELECT.

How do you implement equals/hashCode for a JPA entity?

Prefer an immutable natural key; with only a generated id, equals on a non-null id and a class-level constant hashCode.

equals returns true for the same object, or when the id is non-null and equals the other object’s id. Read through the getter because proxies have empty fields, and check the type with instanceof because a proxy is a subclass. A constant hashCode doesn’t change when the id is assigned on persist. Avoid Lombok’s @Data/default @EqualsAndHashCode, which use every field, lazy associations included.

How do you rename a column on a large table without downtime?

Expand and contract over several releases, because during a rolling deploy two code versions run side by side and the schema must work with both.

  1. A migration adds the new column.
  2. The code writes both columns.
  3. Backfill old rows in small batches so the table isn’t locked for long.
  4. The code reads the new column.
  5. Stop writing the old column.
  6. A later release drops it.

On MySQL, check whether the ALTER TABLE runs online (ALGORITHM=INSTANT/INPLACE), or use gh-ost or pt-online-schema-change for very large tables.

Useful phrases for interviews

  • “JPA is just the specification; Hibernate is the implementation we actually run.”
  • “With IDENTITY generation Hibernate can’t batch inserts, which is why we moved to sequences on PostgreSQL.”
  • “Schema changes go through Flyway migrations that we review like any other code; Hibernate only validates.”
  • “A bigger connection pool doesn’t make the database faster; past a certain point it just adds contention.”
  • “We keep remote calls outside the transaction so we don’t hold a connection while waiting on the network.”
  • “I use getReferenceById when I only need the foreign key, so we skip a pointless SELECT.”
  • “Once a derived query name needs more than a couple of conditions, I switch to an explicit @Query.”
  • “Entity equality is based on the id, with a constant hashCode so it survives the move from transient to managed.”

Next up: ORM and JPA part 2: entity relationships, owning sides and mappedBy.


Notes based on the Fundamentals of Backend course (Ronin Engineer), rewritten in my own words.