3.2. Finding Persistent Objects
It's time to throw the giant lever into reverse and look at how you load data from a database into Java objects.
Use Hibernate Query Language to get an object-oriented view of the contents of your mapped database tables. These might have started out as objects persisted in a previous session, or they might be data that came from completely outside your application code.
3.1.1. How do I do that?
Example 3-5 shows 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 the previous program.
Example 3-5. QueryTest.java
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 return session.find("from com.oreilly.hh.Track as track " + 26 "where track.playTime <= ?", 27 length, Hibernate.TIME); 28 } 29 30 /** 31 * Look up and print some ... |
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.