SteelReed

Search

Search posts, questions…

4. Database & SQL

ORM and JPA: JDBC, Hibernate, entities and repositories

Why ORM exists, what JDBC, JPA, Hibernate and Spring Data JPA are, how to define entities, repositories and services, how to size the connection pool, manage the schema with Flyway and write equals/hashCode for entities.

17 Nov 20268 min readJunior

–

1. The problem

A course service uses hand-written JDBC: 30 SQL statements, each with 15 lines of ResultSet mapping. Adding a status column means editing 9 places, and one gets missed. Moving to JPA removes that bug; the next week, a 2-second payment call inside @Transactional drains the 10-connection pool at 9 a.m.

2. Key idea

Objects and tables are mismatched models (references vs foreign keys, collections vs reverse queries, inheritance vs nothing). An ORM translates between them automatically. But it holds connections, generates SQL and guesses the schema for you, so bugs move from "forgot to map a column" to "can't see the cost".

Layer Responsibility
Spring Data JPA generates repositories, queries from method names, paging
JPA (Jakarta Persistence) the spec: @Entity, EntityManager; doesn't run by itself
Hibernate Spring Boot's default implementation
JDBC + driver the standard interface and each DB's network protocol
Connection pool (HikariCP) keeps connections ready for reuse

@Transactional borrows one connection until commit: hold it long and everyone else queues, even while the DB is idle.

2.1 Five common failures

Failure Symptom Root cause
Pool exhaustion Connection is not available, request timed out after 30000ms, low DB CPU the transaction holds a connection while waiting on I/O
Schema drift works on staging, production lacks a column ddl-auto=update
Wrong enums add one status and old orders change status enums stored by position (ORDINAL, the default)
Batch inserts that don't batch importing 1 million rows = 1 million round trips IDENTITY ids force an immediate INSERT
Entities "vanish" from a Set contains returns false after saving hashCode changes when the id is assigned

2.2 What to use when?

Choice Use when Don't use when
Entity + JpaRepository CRUD, business logic on one aggregate reports across many tables
DTO projections, JDBC, jOOQ read-only screens, reports, bulk updates you need dirty checking and cascades
IDENTITY MySQL, single inserts large imports that need batching
SEQUENCE / UUID v7 batch inserts MySQL has no sequences (Hibernate emulates them with a slow table)
Flyway + validate every shared environment a throwaway prototype

3. In Java

JAVA
@Entity
public class Course {
    @Id @GeneratedValue(strategy = GenerationType.SEQUENCE)  // batchable; on MySQL use IDENTITY
    private Long id;
    @Enumerated(EnumType.STRING)                             // never ORDINAL
    private CourseStatus status;
    protected Course() {}                                    // JPA needs it; class not final
}
 
public interface CourseRepository extends JpaRepository<Course, Long> {
    List<Course> findByStatus(CourseStatus status);          // Spring Data derives the query
}
 
@Transactional                                               // holds a connection until commit
public CourseResponse publish(long id) {
    Course c = repo.findById(id).orElseThrow();
    c.publish();                                             // dirty checking issues the UPDATE
    return CourseResponse.from(c);                           // map to a DTO while the session is open
}

Other languages: C# EF Core; Python SQLAlchemy, Django ORM; Go GORM or sqlc; Node.js Prisma. Spring Boot 3+ uses jakarta.persistence.*; Boot 4 comes with Hibernate 7.

Entity and repository traps
  • equals/hashCode: the id is null before persist, so an id-based hashCode changes after saving. Compare by id when it's non-null, and return a per-class constant from hashCode.
  • Lombok @Data: the generated toString/hashCode walk lazy relations: hidden queries, LazyInitializationException, StackOverflowError with bidirectional relations.
  • UUID v4 fragments InnoDB B-trees; use v7 (Hibernate 7: @UuidGenerator(style = VERSION_7)).
  • save() on an existing entity calls merge and copies the whole state: binding a form straight onto an entity nulls the missing columns.
  • deleteByStatus(...) SELECTs, then deletes entity by entity: 10,000 rows = 10,001 statements. For one DELETE ... WHERE, use @Modifying @Query.
  • getReferenceById returns an id-only proxy without a SELECT; good for setting foreign keys, but a wrong id fails late.
  • Hibernate 6+ detects the dialect itself; Hibernate 7 removed MySQL8Dialect, so drop old hibernate.dialect settings.
  • Interfaces extending JpaRepository don't need @Repository.

4. Working with AI

Delegate to AI: entities generated from migrations, repositories, DTOs and mappers, Testcontainers tests.

Check yourself:

  • No HTTP calls, email or sleeps inside @Transactional.
  • ddl-auto is validate (or none) in every shared environment; the schema goes through Flyway/Liquibase.
  • Enums use EnumType.STRING; entities have no @Data and aren't final.
  • Large imports don't combine IDENTITY with batch_size (it has no effect).
  • Controllers return DTOs, not entities.

5. Exercises

Exercise 1: Review a checkout that's "transactional, so safe"

A 10-connection pool, a payment gateway with p99 of 2 seconds. Find the bug, say how you'd prove it, fix it.

JAVA
@Transactional
public OrderResponse checkout(long orderId) {
    Order order = orderRepository.findById(orderId).orElseThrow();
    PaymentResult r = paymentClient.charge(order.getTotal());   // HTTP, ~2 s
    order.markPaid(r.transactionId());
    return OrderResponse.from(order);
}
Solution to Exercise 1
  • The connection is held through the 2-second HTTP wait: 10 concurrent requests drain the pool, and the 11th waits 30 s then fails. "Rollback if payment fails" is wrong too: a DB rollback doesn't refund money the gateway already took.
  • Proof: a load test with 20 parallel requests shows hikaricp.connections.pending > 0 while DB CPU stays low.
  • Fix: short transaction 1 marks PAYING; call charge outside any transaction, with a timeout and an idempotency key; short transaction 2 writes PAID or FAILED; a reconciliation job handles orders stuck in PAYING.

Exercise 2: Read a pool-exhaustion incident

Monday 9 a.m.: HikariPool-1 - Connection is not available. hikaricp.connections.active = 10 on each pod (10 pods), pending = 40, DB CPU 6%. AI suggests raising maximum-pool-size to 100. Diagnose and act.

Solution to Exercise 2
  • The pool is exhausted while the DB idles: connections are held while not running SQL. A thread dump shows the connection-holding threads waiting on HTTP or a lock inside @Transactional.
  • Don't go to 100: 10 pods × 100 = 1,000 connections, far beyond MySQL's default max_connections (151).
  • 15 minutes: take a thread dump; switch off the waiting feature with a flag or cut the HTTP client timeout.
  • Root fix: move I/O out of transactions, set timeouts on every client, alert when pending > 0 for more than a minute.

Summary

  • An ORM translates objects and tables, but hides connections, SQL and the schema.
  • @Transactional holds a connection until commit; no I/O inside.
  • The schema goes through migrations; Hibernate only validates.
  • STRING enums; SEQUENCE ids or UUID v7 when you need batching.
  • No @Data on entities; be careful with id-based equals.

Next: Part 2: Entity relationships.

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

Practice interview questions on this topic

All JPA & Hibernate questions →All Transactions & Locking questions →

Loading comments…