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

Projection and Aggregation with Criteria

If you’re familiar with SQL, you know what this section title means. If not, fear not; it’s actually pretty simple. Projection simply means that you don’t need all of the information available in a table, so you want to request just part of it. In the case of an object-oriented environment like Hibernate, it means that you don’t need to retrieve an entire object, just one or two of its properties. Aggregation similarly involves identifying properties, but then allows you to ask for statistical information about those properties, such as counting values, or finding maximum, minimum, or average values.

Before Hibernate 3, neither of these were possible without using HQL, so they are a nice addition to the Criteria API. Let’s look at some examples. Starting simply, suppose we want to print all the track titles that contain the letter “v” without bothering to load any entire Track objects.

How do I do that?

Example 8-13 shows a method that uses the projection capability of the criteria API to achieve this.

Example 8-13. Simple projection on a single property

/** * Retrieve the titles of any tracks that contain a particular text string. * * @param text the text to be matched, ignoring case, anywhere in the title. * @param session the Hibernate session that can retrieve data. * @return the matching titles, as strings. */ public static List titlesContainingText(String text, Session session) { Criteria criteria = session.createCriteria(Track.class); criteria.add(Restrictions.like("title", ...

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