8.4. Querying by Example

If you don't want to worry about setting up expressions and criteria, but you've got an object that shows what you're looking for, you can use it as an example and have Hibernate build the criteria for you.

8.1.1. How do I do that?

Let's add another query method to QueryTest.java. Add the code of Example 8-16 to the top of the class where the other queries are.

Example 8-16. Using an example entity to populate a criteria query
 1  /**
 2   * Retrieve any tracks that were obtained from a particular source
 3   * media type.
 4   *
 5   * @param sourceMedia the media type of interest.
 6   * @param session the Hibernate session that can retrieve data.
 7   * @return a list of {@link Track}s meeting the media restriction.
 8   * @throws HibernateException if there is a problem.
 9   */
10  public static List tracksFromMedia(SourceMedia media, Session session)
11      throws HibernateException
12  {
13      Track track = new Track();
14      track.setSourceMedia(media);
15      Example example = Example.create(track);
16
17      Criteria criteria = session.createCriteria(Track.class);
18      criteria.add(example);
19      criteria.addOrder(Order.asc("title"));
20      return criteria.list();
21  }

Lines 13 and 14 create the example Track and set the sourceMedia property to represent what we're looking for. Line 15 wraps it in an Example object. This object gives you some control over which properties will be used in building criteria and how strings are matched. The default behavior is that null properties are ignored, and that ...

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.