Find Data as Objects

Of course, what you really want to do is get the objects you put into the database back out as objects again. Let's see how that works, using Hibernate Query Language to get an object-oriented view of the contents of mapped database tables. These might have started out as objects persisted in a previous session or might be data that came from completely outside your application code.

Example 14 is a program that runs a simple query using the test data we just created. The overall structure will look very familiar because all the Hibernate setup is the same as in the previous program.

Example 14. QueryTest.java

package com.oreilly.hh;

import org.hibernate.*;
import org.hibernate.cfg.Configuration;

import java.sql.Time;
import java.util.*;

/**
 * Retrieve data as objects
 */
public class QueryTest {

    /**
     * Retrieve any tracks that fit in the specified amount of time.
     *
     * @param length the maximum playing time for tracks to be returned.
     * @param session the Hibernate session that can retrieve data.
     * @return a list of {@link Track}s meeting the length restriction.
     * @throws HibernateException if there is a problem.
     */
    public static List tracksNoLongerThan(Time length, Session session)
        throws HibernateException 1 { Query query = session.createQuery("from Track as track " + "where track.playTime <= ?"); query.setParameter(0, length, Hibernate.TIME); return query.list(); } ...

Get Getting Started with Hibernate 3 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.