A read operation tangled with a write path makes it harder to tell whether asking for data can change state. A query separates that request: it retrieves information without changing state, publishing events, or modifying infrastructure. It returns an answer or an error. section 4.6.1
In a hexagonal application, a query is an immutable, self-validating input that carries data but does not execute itself. It implements the Query marker interface; a separate query handler performs the read. A command instead expresses an intent to change state, and the two paths should not share a handler. section 4.3.4 section 4.6.1
Keep query fields primitive at the input boundary so callers and the input-ports module do not depend on domain value objects. A validateThenCreate factory checks the input and returns Either<Error, QueryType>: a valid query on the right or validation errors on the left. section 9.3.1 section 8.3
Listing 9.9 GetArticleByIdQuery: The read-side message
@Getter
@Accessors(fluent = true)
@RequiredArgsConstructor(access = AccessLevel.PRIVATE)
public final class GetArticleByIdQuery
implements Query { #A
private final String articleId; #B
public static Either<Error, GetArticleByIdQuery>
validateThenCreate(final String articleId) {
return Validations.validUuid(articleId, "articleId") #C
.map(GetArticleByIdQuery::new)
.mapLeft(error -> new Error.ValidationErrors(
List.of(error)));
}
}
GetArticleByIdQuery carries a string identifier and validates its UUID format before construction. section 9.3.1
The use case interface extends QueryHandler<Error, Result, QueryType>. Its handler reads through a repository or output port and maps the result to a DTO or read-only projection, rather than exposing a domain entity. The query bus routes the query to its handler. If a caller needs data after a command, use a separate query rather than returning the entity from the command handler. section 4.6.3 section 4.4.3
Listing 4.22 GetArticleByIdHandler implementing the use case directly
@ApplicationService
@RequiredArgsConstructor
final class GetArticleByIdHandler implements GetArticleByIdUseCase {
private final ArticleRepository articleRepository; #A
@Override
public Either<Error, ArticleDTO>
handle(final GetArticleByIdQuery query) {
return this.articleRepository.findById(query.articleId()) #B
.map(ArticleDTO::from); #C
}
}
The article handler reads by ID and maps the result to ArticleDTO. section 4.6.3
Enforce and test the boundary:
- Require query classes to implement the Query marker so they can be routed through the bus; architecture rules can check the structural contract. section 7.5.2
- Test valid factory inputs for a populated right value and invalid inputs for meaningful validation errors on the left. Query construction needs no collaborators or mocks. section 8.3 section 8.8

