Spring Boot
Purpose
Build Spring Boot services with correct transaction boundaries and a JPA layer that does not issue a hundred queries to render a list. Spring's defaults are safe; its abstractions hide the cost of getting them wrong.
When to Use
- Building or reviewing a Spring Boot application.
- Diagnosing lazy-loading exceptions or N+1 query behavior.
- Getting transaction boundaries and propagation right.
- Structuring a test suite that is faster than a full context load per class.
Capabilities
- Constructor injection and bean lifecycle.
- Declarative transactions: propagation, isolation, rollback rules.
- JPA/Hibernate: fetch strategies, entity graphs, projections.
- Configuration properties with validation and profiles.
- Test slices:
@WebMvcTest, @DataJpaTest, Testcontainers.
Inputs
- The service, its entities, and the slow endpoint if there is one.
- Database engine and connection pool configuration.
Outputs
- Services with explicit transaction boundaries.
- Repositories that fetch exactly what the caller needs.
- Tests that load the narrowest context that proves the behavior.
Workflow
- Use constructor injection — Field injection with
@Autowired hides dependencies and makes the class untestable without a container.
- Place
@Transactional at the service layer — Not on the repository (too narrow, one transaction per call) and not on the controller (too wide, the transaction spans view rendering).
- Fetch deliberately — Every association is
LAZY. Then use an entity graph or a fetch join for the specific query that needs it, and a DTO projection for read-only views.
- Validate configuration at startup —
@ConfigurationProperties with @Validated. A missing property should prevent boot, not surface as a null at runtime.
- Test in slices —
@DataJpaTest for repositories against Testcontainers, @WebMvcTest for controllers with mocked services, @SpringBootTest only for the handful of genuine end-to-end paths.
Best Practices
@Transactional on a private or self-invoked method does nothing. Spring proxies the bean; an internal call bypasses the proxy entirely. This is the most common silent transaction bug in Spring.
@Transactional rolls back on unchecked exceptions only, by default. A checked exception commits. Set rollbackFor deliberately.
FetchType.EAGER on an association is a decision made once and paid for on every query. Default to LAZY and fetch on demand.
- Never return entities from a controller. A DTO projection avoids lazy-loading surprises and stops you leaking every column.
- Keep the transaction short. Never make an HTTP call inside one — you are holding a database connection for the duration of someone else's outage.
- Set connection-pool size deliberately. The default is often larger than the database can serve.
Examples
Fetch join with a projection, avoiding both N+1 and over-fetching:
public interface OrderRepository extends JpaRepository<Order, UUID> {
@Query("""
select new com.example.orders.OrderSummary(
o.id, c.name, size(o.lines), sum(l.priceCents * l.quantity))
from Order o
join o.customer c
join o.lines l
where o.status = :status
group by o.id, c.name
""")
List<OrderSummary> findSummaries(@Param("status") OrderStatus status);
}
Transaction boundary at the service, HTTP call outside it:
@Service
@RequiredArgsConstructor
public class RefundService {
private final OrderRepository orders;
private final PaymentGateway gateway;
@Transactional(rollbackFor = Exception.class)
public Refund record(UUID orderId, long amountCents, String gatewayRefundId) {
Order order = orders.findById(orderId).orElseThrow(OrderNotFound::new);
order.applyRefund(amountCents, gatewayRefundId); // invariants live in the entity
return order.latestRefund();
}
// The network call happens outside any transaction.
public Refund refund(UUID orderId, long amountCents) {
String gatewayRefundId = gateway.refund(orderId, amountCents);
return record(orderId, amountCents, gatewayRefundId);
}
}
Notes
spring.jpa.open-in-view defaults to true and keeps a database connection open for the entire request, including view rendering. Turn it off; the lazy-loading exceptions it then reveals are real bugs it was hiding.
- Hibernate's
@BatchSize mitigates N+1 on collections without changing the query — a useful blunt instrument when a fetch join is impractical.
@SpringBootTest loads the entire context. A suite of a hundred such tests is a suite that nobody runs locally.
1---2name: spring-boot3description: Use when building Spring Boot services. Covers dependency injection, transaction boundaries, JPA performance, configuration, validation, and testing slices.4---56# Spring Boot78## Purpose910Build Spring Boot services with correct transaction boundaries and a JPA layer that does not issue a hundred queries to render a list. Spring's defaults are safe; its abstractions hide the cost of getting them wrong.1112## When to Use1314- Building or reviewing a Spring Boot application.15- Diagnosing lazy-loading exceptions or N+1 query behavior.16- Getting transaction boundaries and propagation right.17- Structuring a test suite that is faster than a full context load per class.1819## Capabilities2021- Constructor injection and bean lifecycle.22- Declarative transactions: propagation, isolation, rollback rules.23- JPA/Hibernate: fetch strategies, entity graphs, projections.24- Configuration properties with validation and profiles.25- Test slices: `@WebMvcTest`, `@DataJpaTest`, Testcontainers.2627## Inputs2829- The service, its entities, and the slow endpoint if there is one.30- Database engine and connection pool configuration.3132## Outputs3334- Services with explicit transaction boundaries.35- Repositories that fetch exactly what the caller needs.36- Tests that load the narrowest context that proves the behavior.3738## Workflow39401. **Use constructor injection** — Field injection with `@Autowired` hides dependencies and makes the class untestable without a container.412. **Place `@Transactional` at the service layer** — Not on the repository (too narrow, one transaction per call) and not on the controller (too wide, the transaction spans view rendering).423. **Fetch deliberately** — Every association is `LAZY`. Then use an entity graph or a fetch join for the specific query that needs it, and a DTO projection for read-only views.434. **Validate configuration at startup** — `@ConfigurationProperties` with `@Validated`. A missing property should prevent boot, not surface as a null at runtime.445. **Test in slices** — `@DataJpaTest` for repositories against Testcontainers, `@WebMvcTest` for controllers with mocked services, `@SpringBootTest` only for the handful of genuine end-to-end paths.4546## Best Practices4748- `@Transactional` on a private or self-invoked method does nothing. Spring proxies the bean; an internal call bypasses the proxy entirely. This is the most common silent transaction bug in Spring.49- `@Transactional` rolls back on unchecked exceptions only, by default. A checked exception commits. Set `rollbackFor` deliberately.50- `FetchType.EAGER` on an association is a decision made once and paid for on every query. Default to `LAZY` and fetch on demand.51- Never return entities from a controller. A DTO projection avoids lazy-loading surprises and stops you leaking every column.52- Keep the transaction short. Never make an HTTP call inside one — you are holding a database connection for the duration of someone else's outage.53- Set connection-pool size deliberately. The default is often larger than the database can serve.5455## Examples5657**Fetch join with a projection, avoiding both N+1 and over-fetching:**5859```java60public interface OrderRepository extends JpaRepository<Order, UUID> {6162 @Query("""63 select new com.example.orders.OrderSummary(64 o.id, c.name, size(o.lines), sum(l.priceCents * l.quantity))65 from Order o66 join o.customer c67 join o.lines l68 where o.status = :status69 group by o.id, c.name70 """)71 List<OrderSummary> findSummaries(@Param("status") OrderStatus status);72}73```7475**Transaction boundary at the service, HTTP call outside it:**7677```java78@Service79@RequiredArgsConstructor80public class RefundService {8182 private final OrderRepository orders;83 private final PaymentGateway gateway;8485 @Transactional(rollbackFor = Exception.class)86 public Refund record(UUID orderId, long amountCents, String gatewayRefundId) {87 Order order = orders.findById(orderId).orElseThrow(OrderNotFound::new);88 order.applyRefund(amountCents, gatewayRefundId); // invariants live in the entity89 return order.latestRefund();90 }9192 // The network call happens outside any transaction.93 public Refund refund(UUID orderId, long amountCents) {94 String gatewayRefundId = gateway.refund(orderId, amountCents);95 return record(orderId, amountCents, gatewayRefundId);96 }97}98```99100## Notes101102- `spring.jpa.open-in-view` defaults to `true` and keeps a database connection open for the entire request, including view rendering. Turn it off; the lazy-loading exceptions it then reveals are real bugs it was hiding.103- Hibernate's `@BatchSize` mitigates N+1 on collections without changing the query — a useful blunt instrument when a fetch join is impractical.104- `@SpringBootTest` loads the entire context. A suite of a hundred such tests is a suite that nobody runs locally.