16.4. Projection Queries
In many cases returning the full domain object is unnecessary, and only a small subset of attributes are desired by the application. Projection Queries allow a specific subset of attributes (or attribute paths) to be returned. If a projection query is used then the
Query.list()
will not return the whole domain entity (List<Object>
), but instead will return a List<Object[]>
, with each entry in the array corresponding to a projected attribute.
To define a projection query use the
select(...)
method when building the query, as seen in the following example:
Example 16.4. Retrieving title and publication year
// Match all books that have the word "engine" in their title or description // and return only their title and publication year. Query query = queryFactory.from(Book.class) .select(Expression.property("title"), Expression.property("publicationYear")) .having("title").like("%engine%") .or().having("description").like("%engine%") .toBuilder() .build(); // results.get(0)[0] contains the first matching entry's title // results.get(0)[1] contains the first matching entry's publication year List<Object[]> results = query.list();