Volume 3 Exercises: The BackendPractice for Volume 3
0 / 0

Workbench / Volume 3 Exercises: The Backend

V3·49

Persistence: JDBC, JPA & Spring Data

Exercises for Volume 3, chapter 49: the persistence stack; JDBC; JPA mapping; the entity lifecycle and persistence context; lazy and eager loading; transactions; entity identity; Spring Data repositories, specifications and projections; and the nuances behind incidents: N+1, fetch joins, pagination with joins, optimistic locking, batching and connection pools. 9 theory questions, 9 programming exercises, 3 cumulative projects, the concepts the chapter leaves out, and 5 senior-level exercises.

32 exercises · ~15 min to read
Updated Suggest a correction

Start here: how this chapter's exercises work

The four sets and the locking work as before. The code runs on PostgreSQL 16 with the PostgreSQL JDBC driver 42.7.3 on JDK 21. The tables hold 200,000 orders, 600,000 lines and 1,000 customers. Hibernate and Spring Data weren't available offline, so their exercises give expected outputs, marked as such. Every quoted JDBC output is real, and five of them surprise people:

  • Before any query ran, the driver refused to connect: FATAL: invalid value for parameter "TimeZone": "Asia/Calcutta". The JVM's default zone was the legacy alias, which PostgreSQL 16 rejects. Starting with -Duser.timezone=Asia/Kolkata fixed it (P1).
  • P1. Concatenating x' OR '1'='1 into SQL matched all 1,000 customers. The same input through PreparedStatement matched 0.
  • P4. LIMIT 10 on an orders-to-lines join returned [1, 1, 1, 2, 2, 2, 3, 3, 3, 4], which is 4 orders, not 10.
  • P3. OFFSET 190000 took 17.93 ms per page. The keyset query at the same position took 0.73 ms.
  • P8. Read-modify-write at SERIALIZABLE got the balance right (800), but needed 2,721 retries for 800 increments.

The chapter's lab already covered these, and the exercises build on them rather than repeat them:

  • N+1: 201 queries in 47.6 ms against 1 query in 1.1 ms;
  • 10,000 inserts: 2,275 ms with autocommit, 208 ms in one transaction, 89 ms batched, 50 ms with reWriteBatchedInserts, 20 ms with COPY;
  • connections: 7.19 ms to open one against 0.03 ms to reuse it;
  • lost updates fixed by a version column;
  • concurrent increments: 120 of 800 survived read-modify-write, while an atomic UPDATE and FOR UPDATE both reached 800.

Coverage map.

Chapter component Exercises
the persistence stack T1
JDBC; prepared statements; constraints T1, P1, P2
JPA mapping basics T2, P5
entity lifecycle; persistence context T3, P5
lazy and eager loading T4, P6
transactions; isolation T5, P8
entity identity; equals and hashCode T3, P5
Spring Data repositories; derived queries T6, P7
specifications; projections T6, P7
N+1; fetch joins and their limits T4, P6
pagination with joins T7, P3, P4
optimistic and pessimistic locking T8, P8, P9
batching T7, P2
connection pools T9, P9
persistence in other ecosystems T9

Theory

T1. The persistence stack and JDBC

  1. Draw the stack from a Spring Data call down to the socket: - your repository interface; - the Spring Data proxy; - JPA's EntityManager (Hibernate); - the generated SQL; - Spring's transaction manager; - the HikariCP pool; - the JDBC driver; - the PostgreSQL wire protocol, and the server's backend process.

Which layer owns each of: the transaction, the connection, the SQL text, the cache of loaded entities, and parameter binding? 2. Explain JDBC's core objects: DataSource, Connection, PreparedStatement, ResultSet, SQLException with getSQLState(), and try-with-resources. Why does P1's concatenated query return 1,000 rows, while the prepared one returns 0? Does escaping quotes yourself make concatenation safe? 3. Explain P1's connection failure (invalid value for parameter "TimeZone": "Asia/Calcutta"). What does the driver send at startup, why does the JVM's zone matter, and how should TiffinBox store and compare times (timestamptz, Instant, OffsetDateTime)?

T2. JPA mapping basics

  1. Map TiffinBox's schema: - Order with @Entity, @Table, @Id, and a generation strategy (SEQUENCE with allocationSize, against IDENTITY and UUIDs); - @Column(nullable, length); - @Enumerated(EnumType.STRING); - an embedded Money value (@Embeddable); - @Version; - @OneToMany(mappedBy) to OrderLine with cascade and orphanRemoval; - @ManyToOne(fetch = LAZY) to Customer.

Why does IDENTITY disable insert batching (the lab's 89 ms against 2,275 ms)? 2. Why should @Enumerated(EnumType.ORDINAL) be avoided? What do cascade = ALL and orphanRemoval do to lines when an order is saved or a line is removed from the list? Which side owns a bidirectional association? 3. Should the domain model (ch37) be the JPA entity? Compare annotating the domain classes, against separate persistence entities with mappers. What do JPA's requirements (a no-arg constructor, non-final classes for proxies, mutable fields) do to an immutable domain model?

T3. The entity lifecycle, the persistence context and identity

  1. Explain the entity states (new or transient, managed, detached, removed) and the transitions (persist, merge, find, remove, detach, the end of the transaction). What is dirty checking, and when does Hibernate flush (before a query that touches the changed tables, at commit, on flush())?
  2. Predict (expected, Hibernate 6): - em.find(Order.class, 7) == em.find(Order.class, 7) in one transaction; - the same comparison across two transactions; - changing order.status on a managed entity without calling save; - calling merge(detached) and continuing to modify the detached instance.
  3. Write equals and hashCode for entities with generated ids that work in HashSets before and after persisting, and with Hibernate proxies. Compare the options: the id only, a natural key, a class-constant hashCode, and records (why records can't be entities).

T4. Lazy loading, N+1 and fetch joins

  1. Explain FetchType.LAZY and EAGER, the defaults (@ManyToOne and @OneToOne eager; collections lazy), proxies, and LazyInitializationException. Why should every association be lazy by default, with fetching decided per use case?
  2. The lab measured N+1 at 201 queries (47.6 ms) against a join (1.1 ms) and an IN list (1.1 ms). Explain how each fix appears in JPA: - JOIN FETCH in JPQL; - @EntityGraph(attributePaths = "lines"); - @BatchSize and hibernate.default_batch_fetch_size; - DTO projections that select only the needed columns.

How do you detect N+1 in tests? 3. The limits of fetch joins: - fetching two collections at once gives MultipleBagFetchException or a Cartesian product (lines × payments); - a fetch join with pagination gives Hibernate's warning "HHH90003004: firstResult/maxResults specified with collection fetch; applying in memory", loading every row; - duplicate parents (DISTINCT, which Hibernate 6 handles automatically).

What does P4's real LIMIT 10 result explain?

T5. Transactions and isolation in persistence code

  1. Where do transactions belong? @Transactional on application services (ch46), with readOnly = true for queries (Hibernate skips dirty checking, and the driver can route to replicas). What's wrong with spring.jpa.open-in-view=true (Boot's default, with a startup warning)?
  2. Isolation levels in PostgreSQL: - READ COMMITTED (the default: the lab's lost increments, 120 of 800); - REPEATABLE READ (snapshot); - SERIALIZABLE (P8: correct balance 800, with 2,721 40001 retries).

Which anomalies does each prevent, and what must the application do for 40001 serialisation failures? 3. Keep transactions short. What happens to the pool and to locks when a transaction includes an HTTP call to the payment provider (ch45) or waits for user input? How do you combine a database transaction with an external call correctly (ch51's outbox preview)?

T6. Spring Data: repositories, derived queries, specifications and projections

  1. Explain JpaRepository (CRUD, paging, sorting), derived queries (findByStatusAndPlacedAtAfter), @Query with JPQL or native SQL, @Modifying updates (and why they bypass the persistence context), Pageable, Slice, and Page (which runs an extra count query). When do derived query names become a smell?
  2. Dynamic queries: Specifications (Specification<Order> combined with and and or), Querydsl, the Criteria API, and plain SQL with jOOQ or JdbcClient. Build the admin search ("status in …, kitchen = …, placed between …, customer email like …") safely.
  3. Projections: interface projections, class or record DTO projections, dynamic projections (<T> List<T> findBy…(Class<T> type)), and JdbcClient mapping to records. Why do projections fix many performance problems at once (fewer columns, no entities, no dirty checking, no lazy loading)?

T7. Pagination and batching at scale

  1. P3 measured OFFSET at 1.14 ms (row 0), 1.76 ms (row 10,000) and 17.93 ms (row 190,000), against keyset pagination at 0.55–0.85 ms at every position. Explain why OFFSET n reads and discards n rows, why keyset needs a unique sort key and a matching index ((placed_at, id)), and how the cursor is encoded (ch45's T4). What can keyset not do (jump to page 500)?
  2. P2 measured batch sizes on 10,000 inserts in one transaction: 1 → 465 ms, 10 → 78 ms, 100 → 67 ms, 1,000 → 63 ms, 10,000 → 81 ms. Explain the curve. What batch size should TiffinBox configure for Hibernate (hibernate.jdbc.batch_size, order_inserts, order_updates)?
  3. Bulk work: when should code bypass the ORM? Consider COPY (the lab's 20 ms), INSERT … SELECT, UPDATE … WHERE in one statement, ON CONFLICT DO UPDATE (upsert), and processing large result sets with fetchSize and streaming (Stream<T> from a repository with a cursor).

T8. Optimistic and pessimistic locking, deadlocks and job queues

  1. The lab showed a version column turning a lost cancellation into a conflict. In JPA: - @Version makes every update … WHERE id = ? AND version = ?; - zero rows updated throws OptimisticLockException, which Spring translates to ObjectOptimisticLockingFailureException.

How does the version map to ch45's ETag and If-Match, and what should the API return (412) when the client's version is stale, against 409 when a concurrent transaction won? 2. Pessimistic locking: @Lock(PESSIMISTIC_WRITE) (SELECT … FOR UPDATE), lock timeouts (jakarta.persistence.lock.timeout, lock_timeout), NOWAIT, and SKIP LOCKED. P10 measured a job queue with 4 workers and 100 jobs of 10 ms each: FOR UPDATE took 1,280 ms, and FOR UPDATE SKIP LOCKED took 389 ms. Explain why. 3. Deadlocks. P9: two transactions updating rows 1 then 2, and 2 then 1, produced 40P01 ERROR: deadlock detected, and PostgreSQL aborted one, letting the other commit. How do you prevent deadlocks (consistent lock order), and how should code handle them (retry)?

T9. Connection pools, and persistence in other ecosystems

  1. P7: 100 virtual threads sharing a pool of 5 connections, each running a 20 ms query, finished in 449 ms. The longest wait for a connection was 399 ms, with 0 timeouts, and pg_stat_activity showed 6 connections (the pool plus the monitor). Explain: - why the total is about 100 × 20 / 5 ms; - how HikariCP's maximumPoolSize, connectionTimeout, maxLifetime and leakDetectionThreshold behave; - why the pool is the right bulkhead for virtual threads (ch38); - how to size it (cores × 2 + effective disks; the total across instances under max_connections; PgBouncer).
  2. What does the pool do when the database restarts, when a firewall silently drops idle connections, or when a connection leaks (borrowed and never returned)? Which metrics show pool trouble (hikaricp.connections.pending, usage, timeout)?
  3. Compare persistence in other ecosystems: - Python: SQLAlchemy (Core and ORM, unit of work), Django ORM; - Node: Prisma, TypeORM, Drizzle, Knex; - .NET: Entity Framework Core (change tracking, Include for eager loading, AsNoTracking); - Go: database/sql, sqlc, GORM; - Rust: sqlx (compile-time checked SQL), Diesel.

Where do N+1, lazy loading and pool sizing reappear?

Programming exercises

P1. JDBC safely: parameters, time zones and resources

With plain JDBC against PostgreSQL: 1. show the injection difference between a concatenated query and a PreparedStatement with the input x' OR '1'='1; 2. reproduce the time-zone startup failure and fix it; 3. write a DishDao with try-with-resources, Instant-based timestamps, a whitelist for sort columns, and SQLSTATE-based error translation.

P2. Let the database enforce rules, and batch writes

Create TiffinBox's schema with NOT NULL, UNIQUE, CHECK and foreign keys. Then: 1. trigger each constraint and record the SQLSTATEs and messages; 2. map each to a problem detail (ch44, ch48); 3. measure batch sizes 1, 10, 100, 1,000 and 10,000 for 10,000 inserts in one transaction.

P3. Offset against keyset pagination

On 200,000 orders, time 20 page reads at rows 0, 10,000 and 190,000 with OFFSET, and with keyset (WHERE id > ?). Then implement keyset on (placed_at DESC, id DESC) with an opaque cursor, the matching index, and an EXPLAIN showing an index scan.

P4. Pagination with joins, done right

Show the bug: LIMIT 10 on an orders-to-lines join. Then implement "page 20 orders with their lines" correctly in two ways: ids first, then an IN query; and window functions or jsonb_agg in one query. Describe what Hibernate does with join fetch plus setMaxResults (expected).

P5. The persistence context in action

With Hibernate (or as expected output if unavailable), write tests that show: - identity within a transaction (find == find, one SQL); - dirty checking issuing an UPDATE without save; - merge returning a different instance; - LazyInitializationException after the transaction; - an entity disappearing from a HashSet when hashCode uses a generated id; - flush surfacing a constraint violation early.

Count SQL statements with Hibernate statistics.

P6. Killing N+1 four ways

Load 200 orders with their lines and dishes, and render a summary. Measure statement counts and time for: 1. lazy loading in a loop; 2. JOIN FETCH (or @EntityGraph); 3. default_batch_fetch_size=50; 4. a DTO projection in one query.

Use JDBC to simulate each SQL pattern if Hibernate isn't available, and add a test that fails if the statement count exceeds 3.

P7. Spring Data: derived queries, specifications, projections and JdbcClient

Implement: - OrderRepository with a derived query (findByCustomerIdAndStatusIn); - a @Query with a record projection; - an @Modifying bulk expiry query; - specifications for the admin search (T6); - a Slice-based feed; - the same feed with JdbcClient and keyset.

Write @DataJpaTest tests against PostgreSQL (Testcontainers, ch54) and show the SQL each one generates (expected).

P8. Concurrency: isolation, retries and atomic updates

Run 8 threads × 100 increments on one balance with: 1. SERIALIZABLE read-modify-write with a 40001 retry loop (count the retries); 2. an atomic UPDATE; 3. optimistic locking with a version and retries.

Compare correctness, time and retries. Then write a Spring @Retryable (or TransactionTemplate loop) wrapper that retries whole transactions on 40001, 40P01 and optimistic-lock failures, with backoff and a limit.

P9. Deadlocks, SKIP LOCKED and a pool

  1. Reproduce a deadlock between two transactions that lock rows in opposite orders, then fix it with consistent ordering.
  2. Build a job queue on PostgreSQL with 4 workers, comparing FOR UPDATE and FOR UPDATE SKIP LOCKED.
  3. Build a 5-connection pool with a BlockingQueue and 100 virtual threads, measuring the waits and watching pg_stat_activity.
  4. Configure HikariCP for TiffinBox, with reasons.

Cumulative projects (chapters so far: Volume 1, Volume 2, and Volume 3's 33–49)

C1. The order service's persistence adapter

Implement the persistence adapter for ch37's checkout and ordering core: - separate JPA entities (or JdbcClient) with mappers to the immutable domain; - sequence ids with batching; - @Version exposed as the ETag (ch45, ch48); - the outbox table written in the same transaction (ch51 preview); - keyset feeds (P3); - two-step paging with lines (P4); - an atomic stock decrement (P8); - constraint-to-problem mapping (P2); - the retry wrapper (P8); - Flyway migrations; - statement-count tests for every use case (P6).

Combines: ch37's ports, ch44's skeleton, ch45's ETags, ch46's transactions, ch47's Boot defaults, ch48's web layer, and this chapter.

C2. The admin search and export

Build the admin order search: - specifications (or jOOQ) with optional filters (T6); - whitelisted sorting; - keyset pagination with a capped offset fallback for page numbers; - a streaming CSV export of up to 1,000,000 rows with a database cursor (fetchSize, a read-only transaction, projections) through ch48's StreamingResponseBody and CSV converter.

Measure memory and time for the export, and compare with loading all entities.

Combines: Volume 1's file I/O, ch41's memory measurement, ch45's pagination, ch48's streaming, and this chapter.

C3. The job queue and the expiry sweeper

Build TiffinBox's PostgreSQL-backed job queue for "expire unpaid orders after 15 minutes" and "send receipt": - claim jobs with FOR UPDATE SKIP LOCKED and leases (P9); - retries with backoff and a dead state after 5 attempts; - idempotent handlers (ch45); - virtual-thread workers sharing a small pool (P9, ch38); - metrics (queue depth, age of the oldest job, failures); - graceful shutdown (ch47).

Load test with 10,000 jobs and 8 workers.

Combines: ch38's concurrency, ch41's measurement, ch45's idempotency, ch47's lifecycle and metrics, and this chapter.

What the chapter leaves out

Schema migrations

Flyway and Liquibase version the schema alongside code. Rules for zero-downtime changes: - expand and contract: add a nullable column, deploy code that writes both, backfill in batches, then add constraints and drop the old column; - create indexes with CREATE INDEX CONCURRENTLY; - add constraints NOT VALID, then VALIDATE; - set lock_timeout in migrations, so a migration waiting on a lock doesn't block all traffic behind it.

Hibernate's ddl-auto=update is for prototypes only.

Indexes and query plans

P5's real plans: without an index, customer_id = 42 was a Seq Scan taking 9.2 ms. With CREATE INDEX orders_customer, it became a Bitmap Index Scan taking 0.38 ms. Read plans with EXPLAIN (ANALYZE, BUFFERS), and watch for: - sequential scans on large tables; - row estimates far from actual rows (stale statistics: ANALYZE); - sorts spilling to disk.

Index foreign keys (PostgreSQL doesn't do it automatically), and use composite indexes in filter-then-sort order. Partial indexes (WHERE status = 'NEW') and covering indexes (INCLUDE) help too. pg_stat_statements finds the slowest queries in production. Volume 4 covers database internals.

Second-level and query caches

Hibernate's second-level cache (Ehcache, Caffeine through JCache, Infinispan) caches entities across transactions. It's useful for read-mostly reference data (dishes, kitchens), and risky for frequently changing data or multiple instances without invalidation. Prefer explicit application caches (ch53), which you control.

R2DBC and reactive persistence

R2DBC gives non-blocking drivers for reactive stacks (ch48), with Spring Data R2DBC: no lazy loading, no persistence context, simpler mapping. With virtual threads, JDBC's blocking is cheap, so R2DBC matters mainly for already-reactive services.

Multi-tenancy, auditing and soft deletes

  • Multi-tenancy: a tenant column with row-level security (PostgreSQL RLS), schema-per-tenant, or database-per-tenant. Hibernate supports tenant identifiers.
  • Auditing: Spring Data's @CreatedDate, @LastModifiedBy and @EnableJpaAuditing; Hibernate Envers for history tables.
  • Soft deletes: @SoftDelete in Hibernate 6.4+. They complicate unique constraints and queries; consider archive tables instead.

Senior exercises

S1. TiffinBox's persistence standard

Write the standard, covering: - the stack per module type (JPA with separate entities for cores, JdbcClient or jOOQ for reads and reports); - the id strategy; - lazy everything, plus explicit fetch plans; - open-in-view off; - projections for reads; - keyset pagination; - batching settings; - locking choices per data type; - retry rules; - transaction boundaries and no external calls inside; - pool sizing; - migrations; - statement-count tests; - time zones.

Tie each rule to an output.

S2. Review a persistence pull request

A PR adds: - @OneToMany(fetch = EAGER) on Order.lines and Order.payments; - a controller that returns OrderEntity directly as JSON; - @Transactional on a method that calls the payment API and then saves; - "select * from orders where status = '" + status + "' order by " + sort; - a stock decrement by find, setQty(qty - n) and save; - findAll(PageRequest.of(page, 20)) with join fetch for an admin list that supports page 9,000.

Write the review.

S3. Diagnose a slow, flaky order API

Symptoms: p99 rose from 120 ms to 2.5 s after a release. HikariCP pending spikes to 40. Occasional Connection is not available, request timed out after 30000ms. Database CPU is normal, but pg_stat_activity shows many connections idle in transaction. Find the likely causes, the evidence needed, and the fixes.

S4. Teach "the ORM is not magic" with five outputs

Prepare a 20-minute session using: - the lab's N+1 (201 queries); - P4's LIMIT on a join (4 orders); - the lab's lost increments (120 of 800); - P3's offset (17.93 ms); - P10's SKIP LOCKED (1,280 against 389 ms).

S5. Plan a database-health programme

As tech lead for TiffinBox's data layer, plan the next two quarters: - persistence defaults in the starter (S1); - statement-count tests for the top 20 use cases; - pg_stat_statements dashboards and a weekly slow-query review; - index and constraint audits (unindexed foreign keys, missing uniqueness); - the migration linter and zero-downtime playbook; - pool and PgBouncer sizing for autoscaling; - moving job queues to SKIP LOCKED (P10); - an outbox library (ch51); - read replicas for exports; - training (S4).

Give milestones, risks and metrics.