The number one trick with HQL is to remember that you are using
objects not tables.
To help unconfuse myself, I've adopted the convention of making table names plural and entity object names singular. Thus, if I ever use the plural name in an HQL statement, I know I've done something wrong.
This is case, I have a class called Book, and a table called Books. This returns an Iterator. You will get back an Object[] and you'll need to cast the types correctly.
Code:
public static Iterator listBookInfo() {
Session session = HibernateUtil.getSession();
return session.createQuery("select title, description from Book")
.iterate();
}
Or, perhaps you'd like to return all books. In this case, you'd use the Java for-each statement to walk over the list.
Code:
for ( Book b : listBooks() ) { ... }
public static List<Book> listBooks() {
Session session = HibernateUtil.getSession();
return session.createQuery("from Book").list();
}
Fetching a single object is easy, but only one had better match or you get an exception.
Code:
Book book = (Book) session.getNamedQuery("book.getByISBN")
.setString( "isbn", isbn)
.uniqueResult();
// This is how Book is defined...
@Entity
@Table( name = "Books" )
@NamedQuery( name = "book.getByISBN", query="from Book where isbn = :isbn" )
public class Book {...}
As you can see, the HQL notation is a little more terse than SQL, and you're dealing with objects. There's no straight SQL to HQL process that I'm aware of. Start with
from Classname and if you need to add members and where clauses, using
member names.
The trick, in a nutshell, is to use member names instead of column name, and to use entity object class names instead of table names; at that point, the SQL you know and love is very, very close.
Hope this helps,
-wls