Java Reference
In-Depth Information
Selecting an entity
The simplest usage of the select method is to select an entity. To select an entity, you
pass the Root object for the entity into the select method. This is shown in the follow-
ing code snippet:
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery<Item> query = builder.createQuery(Item.class);
Root<Item> root = query.from(Item.class);
query.select(root);
TypedQuery<Item> tq = entityManager.createQuery(query);
This code snippet is self-explanatory. The Root object is passed into the select meth-
od—this coupled with the use of a TypedQuery means that a list of items is returned with
no need to perform any casting.
Selecting a value
Using the select method, you can select a specific value to be retrieved. In listing 11.5
the getAllItemsNames() method retrieved a list of all item names. This was ac-
complished by using the query root to specifically request the itemName attribute. The
slightly convoluted syntax, using the meta-model, ensures that you're requesting a value
that's available in a query root. You can't request a username value if your query root is an
item because an item doesn't have a username. The relevant lines of code from that earlier
example are reprinted as follows:
Root<Item> root = query.from(Item.class);
query.select(root.get(Item_.itemName));
Selecting multiple values
Selecting multiple values is the next logical step. Often you want more than a single
value—usually you need the value along with the key the value is associated with. To do
this, you create a CriteriaQuery instance that's typed as an Object[] . You then use
the CritieriaBuilder instance to construct a CompoundSelection instance and
provide the values you're interested in retrieving. The values can come from any instance
that you're retrieving—if you're doing a join on multiple tables, you can pluck the values
you're interested in from the join. An array of objects is returned by the query, which can
be slightly dangerous because coding errors in dealing with the resulting array are found
only at execution time and not by the compiler. To get a better sense of this, the following
Search WWH ::




Custom Search