O'Reilly logo

Hibernate: A Developer's Notebook by James Elliott

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

8.2. Compounding Criteria

As you might expect, you can add more than one Criterion to your query, and all of them must be satisfied for objects to be included in the results. This is equivalent to building a compound criterion using Expression.conjunction(), as described in Appendix B. As in Example 8-8, we can restrict our results so that the tracks also have to contain a capital "A" somewhere in their title by adding another line to our method.

Example 8-8. A pickier list of short tracks
Criteria criteria = session.createCriteria(Track.class);
criteria.add(Expression.le("playTime", length));
criteria.add(Expression.like("title", "%A%"));
criteria.addOrder(Order.asc("title"));
return criteria.list();

With this in place, we get fewer results (Example 8-9).

Example 8-9. Tracks of seven minutes or less containing a capital A in their titles
qtest:
     [java] Track: "Adagio for Strings (Ferry Corsten Remix)" (Ferry Corsten,
William Orbit, Samuel Barber) 00:06:35, from Compact Disc
     [java] Track:  "Gravity's Angel" (Laurie Anderson) 00:06:06, from Compact Disc

If you want to find any objects matching any one of your criteria, rather than requiring them to fit all criteria, you need to explicitly use Expression.disjunction() to group them. You can build up combinations of such groupings, and other complex hierarchies, using the built-in criteria offered by the Expression class. Check Appendix B for the details. Example 8-10 shows how we'd change the sample query to give us tracks mix of power ...

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