---
title: "Data access and transactions"
chapter: "08"
---

# Data access and transactions

Spring translates low-level data exceptions and provides a common transaction
model across supported technologies.

## Data choices

- `JdbcClient` or `JdbcTemplate`: explicit SQL and mapping.
- Spring Data JDBC: aggregate-focused relational persistence.
- Spring Data JPA: repositories over JPA/Hibernate.
- R2DBC: reactive access for supported relational systems.
- Spring Data modules: consistent repository ideas for other stores.

Choose the model that matches access patterns and team knowledge. A repository
interface does not remove database design.

## Transactions

`@Transactional` normally uses a proxy. A runtime exception rolls back by
default; checked-exception behavior requires deliberate rules. Transaction
propagation controls whether a method joins, creates, or avoids a transaction.
Isolation controls concurrency phenomena.

Keep transactions short. Do not hold a database transaction open while waiting
for a slow network call.

## The dual-write problem

Updating a database and publishing a message are two separate systems. Use an
outbox pattern: write the business change and outbox event in one transaction,
then publish asynchronously with idempotent consumers.

## JPA cautions

Understand entity state, dirty checking, lazy loading, fetching, N+1 queries,
locking, pagination, and flush timing. Do not serialize entities directly from
controllers.

## Feynman check

A transaction is a pencil-and-eraser agreement: either all related database
changes become permanent or they are erased together. A message broker uses a
different notebook, so an outbox safely carries the note across.
