O'Reilly logo

Harnessing Hibernate by James Elliott, Ryan Fowler, Timothy M. O'Brien

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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.

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

/** * Retrieve any tracks associated with artists whose name matches a SQL * string pattern. * * @param namePattern the pattern which an artist's name must match * @param session the Hibernate session that can retrieve data. * @return a list of {@link Track}s meeting the artist name restriction. */ public static List tracksWithArtistLike(String namePattern, Session session) { Criteria criteria = session.createCriteria(Track.class); Criteria artistCriteria = criteria.createCriteria("artists"); ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required