4.2. Persisting Collections

Our first task is to beef up the CreateTest class to take advantage of the new richness in our schema, creating some artists and associating them with tracks.

4.1.1. How do I do that?

To begin with, add some helper methods to CreateTest.java to simplify the task, as shown in Example 4-5 (with changes and additions in bold).

Example 4-5. Utility methods to help find and create artists, and to link them to tracks
 1  package com.oreilly.hh;
 2
 3  import net.sf.hibernate.*;
 4
 5  import net.sf.hibernate.cfg.Configuration;
 6
 7  import java.sql.Time;
 8  import java.util.*;
 9
10  /**
11   * Create more sample data, letting Hibernate persist it for us.
12   */
13  public class CreateTest {
14
15      /** 16 * Look up an artist record given a name. 17 * @param name the name of the artist desired. 18 * @param create controls whether a new record should be created if 19 * the specified artist is not yet in the database. 20 * @param session the Hibernate session that can retrieve data 21 * @return the artist with the specifiedname, or <code>null</code>if no 22 * such artist exists and <code>create</code> is <code>false</code> 23 * @throws HibernateException if there is a problem. 24 */ 25 public static Artist getArtist(String name, boolean create, 26 Session session) 27 throws HibernateException 28 { 29 Query query = session.getNamedQuery( 30 "com.oreilly.hh.artistByName"); 31 query.setString("name", name); 32 Artist found = (Artist)query.uniqueResult(); 33 if (found == null && create) ...

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.