Step 4: Example Queries
In this part we show Hibernate HSQL queries to retrieve information from the database back-end.
(HQL is Hibernate's query language. It uses concepts similar to SQL.)
Query all books
final Session session = sessionFactory.openSession();
session.beginTransaction();
// Retrieve all Books and display their titles.
Query query = session.createQuery("FROM Book");
List books = query.list();
for (Iterator it = books.iterator(); it.hasNext();) {
Book book = (Book) it.next();
System.out.println(book.getTitle());
}
Parameterized query
// Retrieve George Orwell's book.
query = session.createQuery("SELECT book FROM Book book, Writer writ WHERE "
+ " book.title='1984' AND book.author=writ AND writ.name='G. Orwell'");
books = query.list();
// Show some results
System.out.println("There is " + books.size() + " book from G. Orwell in the Library."); // should be 1
System.out.println(books.get(0).getClass().getName());
Book book = (Book) books.get(0);
System.out.println(book.getTitle()); // should be 1984
System.out.println(book.getAuthor().getName()); // should be G. Orwell
Count query
// Count the number of books in the library
query = session.createQuery("SELECT count(allbooks) FROM Library lib LEFT JOIN lib.books AS allbooks "
+ " WHERE lib.name='My Library'");
int count = ((Number) query.uniqueResult()).intValue();
// there should be 2 books
System.out.println("There are " + count + " books in the library");
Next Step
The final step of this tutorial discusses the use of the EMF Resource concept.
Click here to go to the next step.

