Java Reference
In-Depth Information
code snippet returns the itemId along with the itemName —much more useful than just
retrieving the name alone:
CriteriaQuery<Object[]> query = builder.createQuery(Object[].class);
Root<Item> root = query.from(Item.class);
query.select(builder.array(root.get(Item_.itemId),
root.get(Item_.itemName)));
TypedQuery<Object[]> tq = entityManager.createQuery(query);
Selecting wrappers
Working with arrays of objects is problematic because you won't discover errors with the
handling of the array until runtime. Furthermore, depending on the type of data you're deal-
ing with, you might not discover that the array element is being accessed. For example, if
you were retrieving bid start and end dates, you might not realize an error where you acci-
dently grabbed the wrong date/time due to an off-by-one mistake. With wrappers, you can
construct an object just to handle the results of the query. In the example earlier from Ac-
tionBazaar, you used a wrapper to collect all of the values returned by a JOIN expression
into a single object that summarized a winning bid. The relevant code from the section on
joining is shown again in the following listing.
Listing 11.8. Constructing WinningBidWrapper class from a complex query
In this code excerpt you can see that the CriteriaBuilder construct method takes
a class along with the columns to appear in the result set that will then be fed into the class's
constructor. So the list of parameters following the class serves two purposes: to define the
columns to be retrieved and to specify the parameters to the class's constructor. The class
you provide is a regular POJO—it doesn't have to be a JPA entity.
Search WWH ::




Custom Search