A dto is an object of the application layer. What you want is to populate it directly from the db. It is the query side of cqrs, where you don't have a rich domain model like the command side, you just have projections (dtos) suitable for the client. They are the query(read) model.
UPDATE:
These are the objects of the pattern I use, similar to command, but a query has a result:
public interface QueryResult {}
Plain DTO (or a list of them), with the output data for the clients.
public interface Query<QR extends QueryResult> {}
Plain DTO with the input data (search criteria) for executing the query.
public interface QueryHandler <QR extends QueryResult, Q extends Query<QR>> {
public QR handle ( Q query );
}
The object that executes the query.
EXAMPLE:
- App managing data about Employees, Departments, etc. of a Company.
- Use Case: Give me a list of employees (just the name, email, depart, salary) of the employees younger than 30 years with salary greater than 2,000 euros.
Code:
class EmployeeDto {
private String name;
private String email;
private String departmentName;
private double salary;
...
<<getters and setters>>
...
}
class EmployeeDtoList implements QueryResult {
private List<EmployeeDto> employeeDtos;
...
<<getter and setter>>
...
}
class EmployeesByAgeAndSalary implements Query<EmployeeDtoList> {
private Calendar maxAge;
private double minSalary;
...
<<getters and setters>>
...
}
class EmployeesByAgeAndSalaryHandler implements QueryHandler<EmployeeDtoList,EmployeesByAgeAndSalary> {
...
@Override
public EmployeeDtoList handle(EmployeesByAgeAndSalary query) {
...
<<retrieve from the database the data we need to return,
applying the criteria for the age and salary given in the "query" arg>>
...
}
}
--
The facade that the client uses is a mediator (interface with this method):
public <QR extends QueryResult,Q extends Query<QR>> QR executeQuery(Q query);
The mediator would be implemented by a class that manages a query handler registry, so that it redirects the request to the query handler associated to the given query.
It is similar to the command pattern, but with queries.