In cases where we fetch lists of data we should fetch as little data as it is reasonable. What is reasonable amount of data ? If we fetch a list with 25 records and display 3 out of 4 entity properties then we fetch whole entity. But if amount of data is controlled by the user (say up to about 100 records per page) or better something like value list holder with in memory cach is implemented, and if there can be several users then we should really design our domain services to return data needed for displaying the view and performing further operations and not much more. An example of bad design would be a list that displays 5 properties from 2 entities that have together over 15 properties. In this case we fetch up to ten properties without a reason. Some of them may be required to e.g. display details view but not all of them.

In JPA we can solve this issue by querying for individual fields and then working with Object arrays or Tuple objects. We can also use Value Objects constructed using Constructor Expressions. This gives us easier refactoring and maintenance, it is much easier to work with Value Object then array. But prior to JPA 2.1 we were limited to JPQL Constructor expressions. Let’s say we have a Customer entity that references Order entity and a few others and we want to display list of customer (represented by customer name) orders with order date and id. In JPA 2.1 we could do:

This does not solve cases where we must use Criteria API or Native Queries. Starting from JPA 2.1 we can use Constructor Expression !

Same query as above written in Criteria API (JPA 2.1):

Here we use CritieriaBuilder.construct method that takes Class to be constructed and constructor parameters.

If we would need to make a Native Query then we must use the new @ConstructorResult annotation:

@ConstructorResult also requires target class and an array of @ColumnResult annotations that point to column names from the query that will be constructor parameter values. Order of @ColumnResult annotations is important and must be the same in Value Object constructor.

Have a nice day 😉