Commands change state; queries return data. Keeping those jobs separate gives handlers focused responsibilities and prevents callers from retrieving domain objects through command interfaces. section 4.6 section 4.4.3
Keep the boundary explicit in use-case contracts:
- Return Either<Error, Void> from a command: its right side signals success without returning business data, while its left side exposes typed failure. section 4.3.1
- Return data from a query. If a caller needs information after a command, give that request its own query use case and handler. section 4.6 section 4.4.3
- Use @Transactional(readOnly = true) on query handlers and an ordinary transactional boundary on command handlers to reinforce the distinction at runtime. section 6.3.5
Publishing an article
A publish command can load an article, invoke its domain behavior, and save it while returning Either<Error, Void>. A caller that later needs article data uses a separate query. section 4.4.3 section 4.6
Listing 6.10 @Transactional to enforce CQS
@ApplicationService
@RequiredArgsConstructor
@Transactional(readOnly = true) #A
final class GetArticleByIdHandler
implements GetArticleByIdUseCase {
// ...
}
The query handler’s read-only transaction makes an attempted repository write fail at the database level. section 6.3.5
