8.3. 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.1.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 SQL string pattern.

Let's add a new method to QueryTest.java to implement this. Add the method shown in Example 8-13 after the end of the tracksNoLongerThan() method.

Example 8-13. Filtering tracks based on their artist associations
 1 /** 2 * Retrieve any tracks associated with artists whose name matches a 3 * SQL string pattern. 4 * 5 * @param namePattern the pattern which an artist's name must match 6 * @param session the Hibernate session that can retrieve data. 7 * @return a list of {@link Track}s meeting the artist name restriction. 8 * @throws HibernateException if there is a problem. 9 */ 10 public static List tracksWithArtistLike(String namePattern, Session session) 11 throws HibernateException ...

Get Hibernate: A Developer's Notebook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.