Building a REST API that works is easy. You create an entity, a repository, a controller, and GET /customers returns data.
Building an API that is good is a different challenge. A good API doesn't fall over when the table grows to two million rows. It returns the same error format every time something goes wrong. It keeps money consistent when a request fails halfway. It evolves its database schema without breaking production, and it comes with tests that let you change code without fear.
This article walks through the practices that take a Spring Boot service from "it works on my machine" to "I'd be comfortable running this in production." Every concept comes with code you can adapt.
What we'll cover:
- API refinements: pagination, filtering, DTO mapping, versioning and OpenAPI documentation
- Centralized exception handling with consistent error responses
- The data layer in depth: relationships, transactions, query optimization and schema migrations
- Testing (unit and integration) and structured logging
Prerequisites: basic Java, Spring Boot, JPA and REST knowledge. Examples use Java 17+, Spring Boot 3.x, Maven and PostgreSQL.
The running example
To keep things connected, every example uses a small banking domain:
- A Customer has many Accounts
- An Account has many Transactions
A package-by-feature layout keeps layer boundaries clear:
com.example.bank
├── customer
│ ├── CustomerController.java (HTTP concerns only)
│ ├── CustomerService.java (business rules, transactions)
│ ├── CustomerRepository.java (data access)
│ ├── Customer.java (entity)
│ ├── CustomerMapper.java (entity <-> DTO)
│ └── dto
├── account
├── transaction
└── common
├── exception (custom exceptions, global handler)
└── web (PageResponse, filters)
Part 1: API Refinements
1.1 Pagination
The problem. GET /customers that returns every row works with 10 customers. With 2 million, it exhausts memory, hammers the database and freezes the client. Never return unbounded lists.
The solution. Spring Data JPA supports pagination out of the box through Pageable:
public interface CustomerRepository extends JpaRepository<Customer, Long> {
Page<Customer> findByLastNameContainingIgnoreCase(String lastName, Pageable pageable);
}
@GetMapping
public PageResponse<CustomerResponse> list(
@PageableDefault(size = 20, sort = "id") Pageable pageable) {
return customerService.findAll(pageable);
}
The client calls:
GET /api/v1/customers?page=0&size=20&sort=lastName,asc
page is zero-based, size is the page size, and sort takes field,direction. You can repeat sort for multiple fields.
Protect yourself from a client asking for size=1000000 with one setting:
spring:
data:
web:
pageable:
max-page-size: 100
Don't return Page<Entity> directly. Spring's Page serializes into a bulky structure that can change between versions, and returning entities leaks your persistence model. Define a stable wrapper instead:
public record PageResponse<T>(
List<T> content,
int page,
int size,
long totalElements,
int totalPages,
boolean last) {
public static <T> PageResponse<T> from(Page<T> page) {
return new PageResponse<>(
page.getContent(), page.getNumber(), page.getSize(),
page.getTotalElements(), page.getTotalPages(), page.isLast());
}
}
@Transactional(readOnly = true)
public PageResponse<CustomerResponse> findAll(Pageable pageable) {
return PageResponse.from(
customerRepository.findAll(pageable).map(customerMapper::toResponse));
}
A typical response:
{
"content": [
{ "id": 1, "firstName": "Sita", "lastName": "Sharma", "email": "sita@example.com" }
],
"page": 0,
"size": 20,
"totalElements": 134,
"totalPages": 7,
"last": false
}
Page vs Slice. A Page runs an extra COUNT(*) query to calculate totals. That is useful for "page 3 of 7" interfaces but can be expensive on huge tables. A Slice skips the count and only tells you whether a next page exists, which is ideal for infinite scroll.
Watch out for unvalidated sort fields. sort=doesNotExist throws an error and exposes internals. For public APIs, whitelist the fields clients may sort on.
1.2 Filtering
Clients want requests like this, with every filter optional and any combination valid:
GET /accounts?type=SAVINGS&status=ACTIVE&minBalance=1000
Derived query methods such as findByStatusAndType(...) work for simple cases, but with four optional filters you would need sixteen methods. JPA Specifications solve this cleanly.
Extend JpaSpecificationExecutor:
public interface AccountRepository
extends JpaRepository<Account, Long>, JpaSpecificationExecutor<Account> {
}
Write one small specification per filter. Each returns null when the filter is absent, and Spring ignores nulls when combining:
public final class AccountSpecs {
private AccountSpecs() {}
public static Specification<Account> hasType(AccountType type) {
return (root, query, cb) -> type == null ? null : cb.equal(root.get("type"), type);
}
public static Specification<Account> hasStatus(AccountStatus status) {
return (root, query, cb) -> status == null ? null : cb.equal(root.get("status"), status);
}
public static Specification<Account> balanceAtLeast(BigDecimal min) {
return (root, query, cb) ->
min == null ? null : cb.greaterThanOrEqualTo(root.get("balance"), min);
}
}
Combine them in the service:
@Transactional(readOnly = true)
public PageResponse<AccountResponse> search(AccountFilter filter, Pageable pageable) {
Specification<Account> spec = Specification
.where(AccountSpecs.hasType(filter.type()))
.and(AccountSpecs.hasStatus(filter.status()))
.and(AccountSpecs.balanceAtLeast(filter.minBalance()));
return PageResponse.from(
accountRepository.findAll(spec, pageable).map(accountMapper::toResponse));
}
The filter is a record that Spring binds from query parameters automatically:
public record AccountFilter(AccountType type, AccountStatus status, BigDecimal minBalance) {}
@GetMapping
public PageResponse<AccountResponse> search(AccountFilter filter,
@PageableDefault(size = 20) Pageable pageable) {
return accountService.search(filter, pageable);
}
Now GET /api/v1/accounts?type=SAVINGS&minBalance=1000 works, and leaving out any parameter simply drops that condition.
1.3 Object Mapping: Entities and DTOs
Never expose entities directly from controllers. There are four good reasons:
- Security. An entity may hold fields clients must never see or set, such as
passwordHashorrole. - Stability. Renaming a database column shouldn't break your public API.
- Lazy-loading traps. Serializing an entity can trigger database queries or infinite loops in bidirectional relationships.
- Different shapes. Create requests, update requests and responses rarely have identical fields.
Java records make excellent DTOs because they are immutable and concise. Put validation on the request:
public record CustomerRequest(
@NotBlank @Size(max = 100) String firstName,
@NotBlank @Size(max = 100) String lastName,
@NotBlank @Email String email) {}
public record CustomerResponse(Long id, String firstName, String lastName, String email) {}
Manual mapping is fine for a handful of fields, but gets tedious and error-prone across dozens of DTOs. MapStruct generates mapping code at compile time: no reflection, fast execution, and mistakes become compile errors rather than runtime surprises.
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct</artifactId>
<version>1.5.5.Final</version>
</dependency>
Add the annotation processor to the compiler plugin:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<annotationProcessorPaths>
<path>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-processor</artifactId>
<version>1.5.5.Final</version>
</path>
</annotationProcessorPaths>
</configuration>
</plugin>
Then define the mapper as an interface:
@Mapper(componentModel = "spring")
public interface CustomerMapper {
CustomerResponse toResponse(Customer customer);
@Mapping(target = "id", ignore = true)
@Mapping(target = "accounts", ignore = true)
Customer toEntity(CustomerRequest request);
@Mapping(target = "id", ignore = true)
@Mapping(target = "accounts", ignore = true)
void updateEntity(CustomerRequest request, @MappingTarget Customer customer);
}
componentModel = "spring" turns it into an injectable bean. When field names differ, use @Mapping(source = "customer.email", target = "ownerEmail").
Tip: if you use Lombok with MapStruct, add lombok-mapstruct-binding and list Lombok's processor before MapStruct's, otherwise the generated code won't see your getters.
1.4 API Versioning
Once a client depends on your response shape, changing it can break them. Versioning lets you introduce breaking changes without forcing every client to upgrade at once.
Breaking changes include removing or renaming a field, changing a field's type, or adding a new required parameter. Adding an optional field or a new endpoint is not breaking.
There are four common strategies:
- URI path (
/api/v1/customers): obvious, easy to test and cache, but URLs change between versions. - Custom header (
X-API-Version: 2): clean URLs, but hidden and harder to test in a browser. - Media type (
Accept: application/vnd.bank.v2+json): the purist approach, but complex for most teams. - Query parameter (
/customers?version=2): simple, but easy to forget and pollutes URLs.
For most teams, URI path versioning is the pragmatic choice because everyone, from frontend developers to QA, understands it immediately:
@RestController
@RequestMapping("/api/v1/customers")
public class CustomerController { ... }
When a breaking change is needed, add a v2 controller. Reuse the service layer and change only the DTOs and mapping:
@RestController
@RequestMapping("/api/v2/customers")
public class CustomerV2Controller {
// returns a single fullName field instead of firstName + lastName
}
A few rules of thumb: avoid creating a new version for non-breaking changes, support at most two versions at a time, announce deprecation dates, and version the API contract rather than every internal class.
1.5 API Documentation with OpenAPI
Hand-written documentation goes stale. OpenAPI is a machine-readable description of your API, and springdoc-openapi generates it directly from your code:
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
<version>2.6.0</version>
</dependency>
Start the app and open http://localhost:8080/swagger-ui.html for interactive documentation where you can try endpoints, or http://localhost:8080/v3/api-docs for the raw OpenAPI JSON.
Describe your API once:
@Configuration
public class OpenApiConfig {
@Bean
OpenAPI bankOpenApi() {
return new OpenAPI().info(new Info()
.title("Bank Service API")
.version("v1")
.description("Customers, accounts and transactions"));
}
}
Then annotate controllers and DTOs:
@Tag(name = "Customers", description = "Manage bank customers")
@RestController
@RequestMapping("/api/v1/customers")
public class CustomerController {
@Operation(summary = "Get a customer by id")
@ApiResponses({
@ApiResponse(responseCode = "200", description = "Customer found"),
@ApiResponse(responseCode = "404", description = "Customer not found",
content = @Content(schema = @Schema(implementation = ApiError.class)))
})
@GetMapping("/{id}")
public CustomerResponse get(@PathVariable Long id) {
return customerService.get(id);
}
}
public record CustomerRequest(
@Schema(example = "Sita") @NotBlank String firstName,
@Schema(example = "Sharma") @NotBlank String lastName,
@Schema(example = "sita@example.com") @Email @NotBlank String email) {}
A good habit: document error responses as carefully as the happy path. Frontend and QA engineers rely on them.
Part 2: Centralized Exception Handling
The problem
Without a strategy, errors look different everywhere. One endpoint returns a stack trace, another a plain string, another an empty 500. Clients can't handle that reliably. And scattering try/catch blocks through every controller duplicates code.
The solution: one handler, one format
Spring lets you handle exceptions for all controllers in one place with @RestControllerAdvice.
Step 1: define one error shape.
public record ApiError(
Instant timestamp,
int status,
String error,
String message,
String path,
List<FieldViolation> violations) {
public record FieldViolation(String field, String message) {}
public static ApiError of(HttpStatus status, String message, String path) {
return new ApiError(Instant.now(), status.value(), status.getReasonPhrase(),
message, path, List.of());
}
}
Spring 6 also ships ProblemDetail, an implementation of the standard RFC 9457 "Problem Details" format. You can use it instead of a custom record. What matters is that every error uses the same shape.
Step 2: create meaningful exceptions.
public class ResourceNotFoundException extends RuntimeException {
public ResourceNotFoundException(String resource, Object id) {
super("%s with id %s not found".formatted(resource, id));
}
}
public class ConflictException extends RuntimeException {
public ConflictException(String message) { super(message); }
}
public class BusinessRuleException extends RuntimeException {
public BusinessRuleException(String message) { super(message); }
}
Throw them from the service layer, where business rules live:
public CustomerResponse get(Long id) {
return customerRepository.findById(id)
.map(customerMapper::toResponse)
.orElseThrow(() -> new ResourceNotFoundException("Customer", id));
}
public CustomerResponse create(CustomerRequest request) {
if (customerRepository.existsByEmail(request.email())) {
throw new ConflictException("Email already registered: " + request.email());
}
// ...
}
Step 3: translate them in a global handler.
1@RestControllerAdvice
2@Slf4j
3public class GlobalExceptionHandler {
4
5 @ExceptionHandler(ResourceNotFoundException.class)
6 ResponseEntity<ApiError> notFound(ResourceNotFoundException ex, HttpServletRequest req) {
7 return build(HttpStatus.NOT_FOUND, ex.getMessage(), req);
8 }
9
10 @ExceptionHandler(ConflictException.class)
11 ResponseEntity<ApiError> conflict(ConflictException ex, HttpServletRequest req) {
12 return build(HttpStatus.CONFLICT, ex.getMessage(), req);
13 }
14
15 @ExceptionHandler(BusinessRuleException.class)
16 ResponseEntity<ApiError> businessRule(BusinessRuleException ex, HttpServletRequest req) {
17 return build(HttpStatus.UNPROCESSABLE_ENTITY, ex.getMessage(), req);
18 }
19
20 @ExceptionHandler(MethodArgumentNotValidException.class)
21 ResponseEntity<ApiError> validation(MethodArgumentNotValidException ex, HttpServletRequest req) {
22 List<ApiError.FieldViolation> violations = ex.getBindingResult().getFieldErrors().stream()
23 .map(f -> new ApiError.FieldViolation(f.getField(), f.getDefaultMessage()))
24 .toList();
25 ApiError body = new ApiError(Instant.now(), 400, "Bad Request",
26 "Validation failed", req.getRequestURI(), violations);
27 return ResponseEntity.badRequest().body(body);
28 }
29
30 @ExceptionHandler(MethodArgumentTypeMismatchException.class)
31 ResponseEntity<ApiError> typeMismatch(MethodArgumentTypeMismatchException ex,
32 HttpServletRequest req) {
33 return build(HttpStatus.BAD_REQUEST, "Invalid value for '" + ex.getName() + "'", req);
34 }
35
36 @ExceptionHandler(DataIntegrityViolationException.class)
37 ResponseEntity<ApiError> integrity(DataIntegrityViolationException ex,
38 HttpServletRequest req) {
39 log.warn("Data integrity violation", ex);
40 return build(HttpStatus.CONFLICT, "The request conflicts with existing data", req);
41 }
42
43 // Last resort: never leak internals to the client
44 @ExceptionHandler(Exception.class)
45 ResponseEntity<ApiError> unexpected(Exception ex, HttpServletRequest req) {
46 log.error("Unhandled exception on {}", req.getRequestURI(), ex);
47 return build(HttpStatus.INTERNAL_SERVER_ERROR, "Something went wrong", req);
48 }
49
50 private ResponseEntity<ApiError> build(HttpStatus status, String message,
51 HttpServletRequest req) {
52 return ResponseEntity.status(status)
53 .body(ApiError.of(status, message, req.getRequestURI()));
54 }
55}
A validation failure now looks like this, every time:
{
"timestamp": "2026-11-16T09:30:00Z",
"status": 400,
"error": "Bad Request",
"message": "Validation failed",
"path": "/api/v1/customers",
"violations": [
{ "field": "email", "message": "must be a well-formed email address" },
{ "field": "firstName", "message": "must not be blank" }
]
}
Choosing the right status code
- 200 OK: success with a body
- 201 Created: a resource was created (include a
Locationheader) - 204 No Content: success with nothing to return
- 400 Bad Request: malformed request or failed validation
- 401 Unauthorized: not authenticated
- 403 Forbidden: authenticated but not allowed
- 404 Not Found: the resource doesn't exist
- 409 Conflict: duplicate or state conflict, such as an email that already exists
- 422 Unprocessable Entity: valid format but a business rule is violated, such as insufficient funds
- 500 Internal Server Error: an unexpected failure
Golden rules
- Never expose stack traces or SQL to clients. Log them server-side instead.
- Throw in services, translate in the handler. Controllers stay thin.
- Use unchecked exceptions for business errors so you don't litter method signatures with
throws. - Log at the right level. Expected errors (404, validation) at
WARNorINFO; unexpected ones atERRORwith the stack trace. - Be consistent. The shape of your errors is part of your API contract.
Part 3: The Data Layer in Depth
3.1 Entity relationships
One-to-many and many-to-one is the most common relationship. A customer has many accounts, and the many side owns the foreign key.
1@Entity
2public class Customer {
3 @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
4 private Long id;
5
6 private String firstName;
7 private String lastName;
8 private String email;
9
10 @OneToMany(mappedBy = "customer", cascade = CascadeType.ALL, orphanRemoval = true)
11 private List<Account> accounts = new ArrayList<>();
12
13 // Keep both sides of the relationship in sync
14 public void addAccount(Account account) {
15 accounts.add(account);
16 account.setCustomer(this);
17 }
18
19 public void removeAccount(Account account) {
20 accounts.remove(account);
21 account.setCustomer(null);
22 }
23}
24
25@Entity
26public class Account {
27 @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
28 private Long id;
29
30 private String accountNumber;
31 private BigDecimal balance;
32
33 @Enumerated(EnumType.STRING)
34 private AccountType type;
35
36 @ManyToOne(fetch = FetchType.LAZY, optional = false)
37 @JoinColumn(name = "customer_id")
38 private Customer customer;
39}
Key points:
mappedBymarks the inverse side. Thecustomerfield inAccountowns thecustomer_idcolumn.cascade = ALLpropagates save, update and delete from customer to accounts. Use it only for true parent-child ownership.orphanRemoval = truedeletes an account once it is removed from the customer's list.- Always use
@Enumerated(EnumType.STRING). The defaultORDINALstores 0, 1, 2, so reordering the enum silently corrupts your data. - Use
BigDecimalfor money, neverdouble.
One-to-one:
@OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinColumn(name = "profile_id")
private CustomerProfile profile;
Many-to-many. An account can have many features (SMS alerts, overdraft protection), and a feature belongs to many accounts:
@ManyToMany
@JoinTable(name = "account_feature",
joinColumns = @JoinColumn(name = "account_id"),
inverseJoinColumns = @JoinColumn(name = "feature_id"))
private Set<Feature> features = new HashSet<>();
Use a Set rather than a List for many-to-many. If the link needs its own data, such as "enabled since", model it as a separate entity with two @ManyToOne fields instead.
Fetch types. LAZY loads related data only when it's accessed; EAGER loads it immediately with the parent. JPA defaults @OneToMany and @ManyToMany to lazy, but @ManyToOne and @OneToOne to eager. The best practice is to make everything LAZY and fetch what you need explicitly per query. Eager loading creates surprise queries you can't switch off.
Bidirectional pitfalls. Serializing entities causes infinite recursion (Customer → accounts → customer → ...), which DTOs prevent. And Lombok's @Data on entities generates equals, hashCode and toString methods that touch lazy collections. Prefer @Getter and @Setter, and implement equals/hashCode deliberately.
3.2 Transactions
A transaction is a set of operations that all succeed or all fail together. The classic example is a money transfer:
@Transactional
public void transfer(Long fromId, Long toId, BigDecimal amount) {
Account from = accountRepository.findById(fromId)
.orElseThrow(() -> new ResourceNotFoundException("Account", fromId));
Account to = accountRepository.findById(toId)
.orElseThrow(() -> new ResourceNotFoundException("Account", toId));
if (from.getBalance().compareTo(amount) < 0) {
throw new BusinessRuleException("Insufficient funds");
}
from.setBalance(from.getBalance().subtract(amount));
to.setBalance(to.getBalance().add(amount));
}
If anything throws after the debit, the whole transaction rolls back and money never disappears. Notice there is no save() call: inside a transaction, JPA's dirty checking detects changed entities and writes them at commit.
Where to put @Transactional. On the service layer, never on controllers or repositories. One service method is usually one business operation, which is one transaction.
Read-only transactions. Mark pure reads with @Transactional(readOnly = true). This lets Hibernate skip dirty checking and gives the database room to optimize.
Rollback rules (a very common gotcha). By default, Spring rolls back only for unchecked exceptions. A checked exception will commit! If you need otherwise:
@Transactional(rollbackFor = Exception.class)
Self-invocation doesn't work. @Transactional operates through a proxy, so it only applies when the call comes from another bean:
public void a() {
b(); // calls b() on "this", bypassing the proxy: NO transaction starts
}
@Transactional
public void b() { ... }
Move b() into a separate service, or restructure the code.
Propagation, briefly. REQUIRED (the default) joins the current transaction or starts one. REQUIRES_NEW always starts a fresh one and suspends the current, which is useful rarely, for example writing an audit record that must persist even if the main operation rolls back.
Concurrency and optimistic locking. If two users update the same account at the same moment, the last write silently wins and an update is lost. Add a version column:
@Version
private Long version;
Hibernate then adds WHERE version = ? to updates. If someone else changed the row first, an ObjectOptimisticLockingFailureException is thrown. Map that to 409 Conflict in your global handler so the client can reload and retry.
The dreaded LazyInitializationException:
org.hibernate.LazyInitializationException: could not initialize proxy - no Session
This happens when you touch a lazy relationship after the transaction ended. Fix it by loading what you need inside the service (using a fetch join or entity graph, covered next) and mapping to a DTO before returning. Don't "fix" it by making everything eager, and don't leave Open-Session-In-View enabled:
spring:
jpa:
open-in-view: false
Open-in-view holds a database connection for the entire HTTP request and hides lazy-loading problems until production. Turn it off.
3.3 Query optimization
The N+1 problem is the number one performance killer. Load 50 customers, then read each one's accounts:
List<Customer> customers = customerRepository.findAll(); // 1 query
for (Customer c : customers) {
c.getAccounts().size(); // +50 queries!
}
That's 1 + N queries. It looks fine in development with 5 rows and brings production to its knees with 5,000. To spot it, turn on SQL logging in development and count the queries:
spring:
jpa:
properties:
hibernate:
format_sql: true
logging:
level:
org.hibernate.SQL: DEBUG
Fix 1: JOIN FETCH.
@Query("select c from Customer c left join fetch c.accounts where c.id = :id")
Optional<Customer> findWithAccounts(@Param("id") Long id);
Fix 2: @EntityGraph.
@EntityGraph(attributePaths = "accounts")
Optional<Customer> findById(Long id);
Warning: don't JOIN FETCH a collection together with pagination. Hibernate will paginate in memory (look for warning HHH000104). Use batch fetching instead.
Fix 3: batch fetching. This is excellent alongside pagination:
spring:
jpa:
properties:
hibernate:
default_batch_fetch_size: 50
Instead of one query per customer, Hibernate loads accounts for up to 50 customers per query, turning 51 queries into 2.
Use projections when you don't need the whole entity. If a list screen shows only name and email, don't load 20 columns and every relationship:
public interface CustomerSummary {
Long getId();
String getFirstName();
String getEmail();
}
Page<CustomerSummary> findAllBy(Pageable pageable);
Indexes let the database find rows without scanning the whole table. Index columns you frequently filter, join or sort by:
CREATE INDEX idx_account_customer_id ON account (customer_id);
CREATE UNIQUE INDEX uq_customer_email ON customer (email);
Remember that PostgreSQL does not automatically index foreign keys. Use EXPLAIN ANALYZE on slow queries; a sequential scan on a big filtered table usually means a missing index.
Quick wins:
- Use
existsBy...instead offindBy...when you only need to know whether a row exists. - Enable JDBC batching (
hibernate.jdbc.batch_size=50) withsaveAllfor bulk inserts, and prefer sequences overIDENTITYids at large scale. - Never call repositories inside loops. Fetch in bulk with
findAllById(ids). - Always paginate list endpoints.
3.4 Schema migrations
Setting spring.jpa.hibernate.ddl-auto=update lets Hibernate change your schema automatically. That's fine on a laptop and dangerous everywhere else: it can't rename columns safely, never drops anything and leaves no history. Production databases need controlled, reviewable, repeatable changes.
Flyway is version control for your database. It runs numbered SQL scripts in order and records what has run in a flyway_schema_history table.
<dependency>
<groupId>org.flywaydb</groupId>
<artifactId>flyway-core</artifactId>
</dependency>
<dependency>
<groupId>org.flywaydb</groupId>
<artifactId>flyway-database-postgresql</artifactId>
</dependency>
Place scripts in src/main/resources/db/migration:
V1__create_customer_table.sql
V2__create_account_table.sql
V3__add_phone_number_to_customer.sql
-- V1__create_customer_table.sql
CREATE TABLE customer (
id BIGSERIAL PRIMARY KEY,
first_name VARCHAR(100) NOT NULL,
last_name VARCHAR(100) NOT NULL,
email VARCHAR(255) NOT NULL UNIQUE,
created_at TIMESTAMP NOT NULL DEFAULT now()
);
-- V3__add_phone_number_to_customer.sql
ALTER TABLE customer ADD COLUMN phone_number VARCHAR(20);
Tell Hibernate to validate rather than change the schema:
spring:
jpa:
hibernate:
ddl-auto: validate
flyway:
enabled: true
On startup, Flyway applies pending migrations and Hibernate then checks that your entities match the tables, failing fast if they don't.
Migration rules worth following:
- Never edit a migration that has already been applied. Flyway stores a checksum and will fail. Fix mistakes with a new
Vfile. - One logical change per migration, with a descriptive name.
- Treat migrations as forward-only. Plan your rollback, but implement it as a new migration.
- Make changes backward-compatible. Renaming a column in one release breaks the old version still running during deployment. Use the expand and contract pattern: add the new column, deploy code that writes to both, backfill, switch reads, and drop the old column in a later release.
- Adding a
NOT NULLcolumn to a populated table needs a default value or a backfill step.
Reference data that must exist everywhere belongs in a migration. Test data belongs in tests.
Part 4: Testing and Structured Logging
4.1 The testing pyramid
Aim for many fast unit tests, a healthy set of integration tests for the layers that talk to something real (the web layer, the database), and few broad end-to-end tests. Spring Boot's spring-boot-starter-test already bundles JUnit 5, Mockito, AssertJ and MockMvc.
4.2 Unit tests for the service layer
Unit tests have no Spring context and no database, so they run in milliseconds. Dependencies are replaced with mocks:
1@ExtendWith(MockitoExtension.class)
2class CustomerServiceTest {
3
4 @Mock CustomerRepository customerRepository;
5 @Mock CustomerMapper customerMapper;
6 @InjectMocks CustomerService customerService;
7
8 @Test
9 void create_throwsConflict_whenEmailAlreadyExists() {
10 CustomerRequest request = new CustomerRequest("Sita", "Sharma", "sita@example.com");
11 when(customerRepository.existsByEmail("sita@example.com")).thenReturn(true);
12
13 assertThatThrownBy(() -> customerService.create(request))
14 .isInstanceOf(ConflictException.class)
15 .hasMessageContaining("sita@example.com");
16
17 verify(customerRepository, never()).save(any());
18 }
19
20 @Test
21 void get_throwsNotFound_whenCustomerMissing() {
22 when(customerRepository.findById(99L)).thenReturn(Optional.empty());
23
24 assertThatThrownBy(() -> customerService.get(99L))
25 .isInstanceOf(ResourceNotFoundException.class);
26 }
27}
Structure tests as arrange, act, assert, and name them by behavior. create_throwsConflict_whenEmailAlreadyExists tells you what broke without opening the file.
Cover the unhappy paths, not just the happy one. For every service method, test the success case, not found, validation or business rule failures, conflicts and boundary values (zero, negative, exactly at the limit).
4.3 Web layer tests with MockMvc
@WebMvcTest loads only the controller layer, with the service mocked. It verifies routing, validation, status codes and JSON without touching a database:
1@WebMvcTest(CustomerController.class)
2class CustomerControllerTest {
3
4 @Autowired MockMvc mockMvc;
5 @MockBean CustomerService customerService; // @MockitoBean in Spring Boot 3.4+
6
7 @Test
8 void get_returns404_whenCustomerNotFound() throws Exception {
9 when(customerService.get(99L))
10 .thenThrow(new ResourceNotFoundException("Customer", 99L));
11
12 mockMvc.perform(get("/api/v1/customers/99"))
13 .andExpect(status().isNotFound())
14 .andExpect(jsonPath("$.status").value(404))
15 .andExpect(jsonPath("$.message").value("Customer with id 99 not found"));
16 }
17
18 @Test
19 void create_returns400_whenEmailInvalid() throws Exception {
20 String body = """
21 { "firstName": "Sita", "lastName": "Sharma", "email": "not-an-email" }
22 """;
23
24 mockMvc.perform(post("/api/v1/customers")
25 .contentType(MediaType.APPLICATION_JSON)
26 .content(body))
27 .andExpect(status().isBadRequest())
28 .andExpect(jsonPath("$.violations[0].field").value("email"));
29 }
30}
Because @WebMvcTest also picks up your @RestControllerAdvice, these tests verify your error responses too.
4.4 Repository tests against a real database
Test your queries, specifications and mappings against the same engine you run in production. H2 behaves differently from PostgreSQL in functions, types and locking, so tests can pass on H2 and fail in production. Testcontainers runs the real database in Docker:
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>postgresql</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
1@DataJpaTest
2@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
3@Testcontainers
4class AccountRepositoryTest {
5
6 @Container
7 @ServiceConnection
8 static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:16");
9
10 @Autowired AccountRepository accountRepository;
11 @Autowired CustomerRepository customerRepository;
12
13 @Test
14 void search_filtersByTypeAndMinBalance() {
15 Customer customer = customerRepository.save(
16 new Customer("Sita", "Sharma", "sita@example.com"));
17 accountRepository.save(new Account("111", new BigDecimal("500"), AccountType.SAVINGS, customer));
18 accountRepository.save(new Account("222", new BigDecimal("5000"), AccountType.SAVINGS, customer));
19 accountRepository.save(new Account("333", new BigDecimal("9000"), AccountType.CURRENT, customer));
20
21 Specification<Account> spec = Specification
22 .where(AccountSpecs.hasType(AccountType.SAVINGS))
23 .and(AccountSpecs.balanceAtLeast(new BigDecimal("1000")));
24
25 Page<Account> result = accountRepository.findAll(spec, PageRequest.of(0, 10));
26
27 assertThat(result.getContent())
28 .extracting(Account::getAccountNumber)
29 .containsExactly("222");
30 }
31}
@ServiceConnection (Spring Boot 3.1+) wires the container's connection details automatically. Since Flyway runs on startup, your migrations get tested too.
4.5 Full integration tests
@SpringBootTest starts the whole application and exercises it end to end through real HTTP, services and database:
1@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
2@Testcontainers
3class CustomerApiIT {
4
5 @Container
6 @ServiceConnection
7 static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:16");
8
9 @Autowired TestRestTemplate restTemplate;
10
11 @Test
12 void createThenFetchCustomer() {
13 CustomerRequest request = new CustomerRequest("Ram", "Thapa", "ram@example.com");
14
15 ResponseEntity<CustomerResponse> created =
16 restTemplate.postForEntity("/api/v1/customers", request, CustomerResponse.class);
17 assertThat(created.getStatusCode()).isEqualTo(HttpStatus.CREATED);
18
19 Long id = created.getBody().id();
20 ResponseEntity<CustomerResponse> fetched =
21 restTemplate.getForEntity("/api/v1/customers/" + id, CustomerResponse.class);
22
23 assertThat(fetched.getBody().email()).isEqualTo("ram@example.com");
24 }
25
26 @Test
27 void duplicateEmailReturns409() {
28 CustomerRequest request = new CustomerRequest("Gita", "Rai", "gita@example.com");
29 restTemplate.postForEntity("/api/v1/customers", request, CustomerResponse.class);
30
31 ResponseEntity<ApiError> second =
32 restTemplate.postForEntity("/api/v1/customers", request, ApiError.class);
33
34 assertThat(second.getStatusCode()).isEqualTo(HttpStatus.CONFLICT);
35 }
36}
A useful convention: name unit tests *Test (run by Maven Surefire on every build) and integration tests *IT (run by Failsafe during mvn verify), so you can run fast tests constantly and slow ones in CI.
4.6 Testing best practices
- Test behavior, not implementation. Avoid verifying every internal call.
- Keep tests independent. No test should depend on another's data or on run order.
- Avoid
Thread.sleep. Use Awaitility for asynchronous assertions. - Don't test the framework. You don't need a test proving
save()saves. - Make failures explain themselves. Descriptive AssertJ assertions beat bare
assertTrue. - Run the suite in CI on every pull request.
4.7 Structured logging
When something breaks at 2 a.m., logs are often all you have. In a banking domain they also support auditing and incident response.
Log levels:
ERROR: something failed and needs attentionWARN: unexpected but handled, such as a retryINFO: key business events, such as "transfer completed"DEBUG: detailed diagnostics for developers, off in productionTRACE: extremely fine-grained, rarely used
logging:
level:
root: INFO
com.example.bank: DEBUG
Use SLF4J with placeholders, not string concatenation. Placeholders are only built when the level is enabled, so disabled logs cost almost nothing. Pass the exception as the last argument to capture the stack trace:
@Service
@Slf4j
public class TransferService {
public void transfer(Long fromId, Long toId, BigDecimal amount) {
log.info("Transfer started from={} to={} amount={}", fromId, toId, amount);
try {
// ...
log.info("Transfer completed from={} to={}", fromId, toId);
} catch (RuntimeException ex) {
log.error("Transfer failed from={} to={}", fromId, toId, ex);
throw ex;
}
}
}
What never to log: passwords, tokens, API keys, full card numbers, PINs, CVVs and personal data in plain form. Mask or omit them (****1234). In banking, this is a compliance matter, not a nicety.
From plain text to structured logs. A plain line is readable to humans but hard for machines:
2026-11-16 09:30:01 INFO TransferService - Transfer completed from=1 to=2 amount=500
A structured log is machine-parseable, typically JSON, so tools like Elasticsearch, Loki or Datadog can search and filter by field:
{
"@timestamp": "2026-11-16T09:30:01Z",
"level": "INFO",
"logger": "com.example.bank.transfer.TransferService",
"message": "Transfer completed",
"correlationId": "7c9e6679-7425-40de-944b-e07fc1f90ae7",
"fromAccountId": 1,
"toAccountId": 2,
"amount": 500
}
Now you can ask "show me every ERROR for correlation ID X" or "how many transfers failed in the last hour" with a simple query.
Spring Boot 3.4 and later include structured logging out of the box. One property is enough:
logging:
structured:
format:
console: ecs # also: logstash, gelf
On older versions, use logstash-logback-encoder with a logback-spring.xml.
Correlation IDs with MDC. A single request touches many classes and produces many log lines. A correlation ID ties them together. SLF4J's MDC (Mapped Diagnostic Context) attaches key-value pairs to every log line written by the current thread:
1@Component
2public class CorrelationIdFilter extends OncePerRequestFilter {
3
4 private static final String HEADER = "X-Correlation-Id";
5
6 @Override
7 protected void doFilterInternal(HttpServletRequest request,
8 HttpServletResponse response,
9 FilterChain chain) throws ServletException, IOException {
10 String id = Optional.ofNullable(request.getHeader(HEADER))
11 .filter(s -> !s.isBlank())
12 .orElse(UUID.randomUUID().toString());
13
14 MDC.put("correlationId", id);
15 response.setHeader(HEADER, id);
16 try {
17 chain.doFilter(request, response);
18 } finally {
19 MDC.clear(); // threads are pooled, so always clean up
20 }
21 }
22}
With structured logging enabled, every line for that request carries the same ID. Returning it in a response header (and in your ApiError) means a support engineer can ask a customer for it and find the full story in seconds.
Logging best practices:
- Log events, not noise. One meaningful line beats ten "entering method" lines.
- Log once. Don't log and rethrow at every layer; let the global handler log it.
- Include context: ids, outcomes and durations.
- Use consistent field names across services.
- Treat logs as a product. Someone will read them under pressure.
Common Mistakes at a Glance
- Returning entities from controllers. Leaks fields and invites lazy-loading errors. Use DTOs and MapStruct.
- Unpaginated list endpoints. Memory and latency blow-ups. Use
Pageablewith a maximum size. ddl-auto=updatein production. Untracked, unsafe schema changes. Use Flyway andvalidate.- Eager fetching everywhere. Hidden extra queries. Use
LAZYwith fetch joins or entity graphs. @Transactionalon controllers. Wrong boundary and long transactions. Put it on services.- Returning
nullinstead of throwing. Silent failures. Throw, and handle globally. doublefor money. Rounding errors. UseBigDecimal.- Testing only on H2. Passes locally, fails on PostgreSQL. Use Testcontainers.
- Logging sensitive data. A compliance breach. Mask or omit.
- Testing only the happy path. Bugs hide in error paths. Test not-found, validation and conflict cases.
Production-Readiness Checklist
Before you ship an endpoint, ask yourself:
- Does any controller return an entity directly?
- Is every list endpoint paginated, with a maximum page size?
- Are all relationships lazy, with
open-in-viewturned off? - Is
@Transactionalon service methods, withreadOnly = truefor reads? - Have I checked the SQL log for N+1 queries?
- Do money fields use
BigDecimaland enums useEnumType.STRING? - Do schema changes go through Flyway only, without edited old migrations?
- Does every error return the same shape with the correct status code?
- Do tests cover both success and failure paths?
- Is anything sensitive leaking into the logs?
- Does Swagger UI show accurate endpoints, examples and error responses?
Key Takeaways
- Design the contract deliberately. Paginate, filter, version and document your API.
- One error format, produced in one place. Consistency is part of the API contract.
- The database is a first-class part of your design. Relationships, transactions, queries and migrations all deserve care.
- Tests let you change code safely. Test each layer appropriately and test failure as much as success.
- Logs are your eyes in production. Structure them, correlate them and keep secrets out of them.
None of these practices is exotic, but together they separate a demo from a service you can trust. Start with the ones that hurt most in your current project, usually pagination, error handling and N+1 queries, then build outward.
If you found this useful, follow for more on Java and Spring Boot. Next up: caching, messaging, scheduled jobs, resilient calls to external APIs, and securing your service with Spring Security and Actuator.