8.4. Applying Criteria to Associations
So far we've been looking at the properties of a single class in forming our criteria. Of course, in our real
systems, we've got a rich set of associations between objects, and
sometimes the details we want to use to filter our results come from these
associations. Fortunately, the criteria query API
provides a straightforward way of performing such searches.
8.4.1. How do I do that?
Let's suppose we're interested in finding all the tracks
associated with particular artists. We'd want our criteria to look at
the values contained in each Track's artists property, which is
a collection of associations to Artist objects.
Just to make it a bit more fun, let's say we want to be able to find
tracks associated with artists whose name property matches a particular substring
pattern.
Let's add a new method to QueryTest.java to implement this. Add the
method shown in Example 8-16 after the end of the
tracksNoLongerThan( ) method.
Example 8-16. Filtering tracks based on their artist associations
Code View: /** |
To see all this in action, we need to make one more change. Modify
the main( ) method so that it invokes this
new query, as shown in Example 8-17.
Example 8-17. Calling the new track artist name query
... |
Running ant qtest now gives the
results shown in Example 8-18.
Example 8-18. Tracks associated with an artist whose name ends with the
letter "n"
qtest: |
8.4.2. What just happened?
NOTE
You can also create aliases for the associations with which
you're working, and use those aliases in expressions. This starts
getting complex but it's useful. Explore it someday.
If you look at the lists of artists for each of the three tracks
that were found, you'll see that at least one of them has a name ending
in "n" as we requested (they're in bold type for easier recognition in
this printing). Also notice that we have access to all the artists
associated with each track, not just the ones that matched the name criterion. This is what you'd expect and
want, given that we've retrieved the actual Track
entities. You can run criteria queries in a different mode, by
calling setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP), which causes it to
return a list of hierarchical Maps in which the
criteria at each level have filtered the results. This goes beyond the
scope of this book, but there are some examples of it in the reference
and API documentation.
|
No comments:
Post a Comment