4.3. Retrieving Collections

You might expect that getting the collection information back out of the database is similarly easy. You'd be right! Let's enhance our QueryTest class to show us the artists associated with the tracks it displays. Example 4-8 shows the appropriate changes and additions in bold. Little new code is needed.

Example 4-8. QueryTest.java enhanced in order to display artists associated with tracks
 1  package com.oreilly.hh;
 2
 3  import net.sf.hibernate.*;
 4  import net.sf.hibernate.cfg.Configuration;
 5
 6  import java.sql.Time;
 7  import java.util.*;
 8
 9  /**
10   * Retrieve data as objects
11   */
12  public class QueryTest {
13
14      /**
15       * Retrieve any tracks that fit in the specified amount of time.
16       *
17       * @param length the maximum playing time for tracks to be returned.
18       * @param session the Hibernate session that can retrieve data.
19       * @return a list of {@link Track}s meeting the length restriction.
20       * @throws HibernateException if there is a problem.
21       */
22      public static List tracksNoLongerThan(Time length, Session session)
23          throws HibernateException
24      {
25          Query query = session.getNamedQuery(
26                            "com.oreilly.hh.tracksNoLongerThan");
27          query.setTime("length", length);
28          return query.list();
29      }
30
31      /** 32 * Build a parenthetical, comma-separated list of artist names. 33 * @param artists the artists whose names are to be displayed. 34 * @return formatted list, or an empty string if the set was empty. 35 */ 36 public static String listArtistNames(Set ...

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.