Friday, August 29, 2008

left/right outer join in Hibernate

Hibernate is great, but while HQL automates a lot of SQL, sometimes you run into things you can do in SQL that are hard in HQL...

For example, I wanted to do a left outer join between two tables, but I don't understand how to set one-to-one or one-to-many relationships in the XML config files for Hibernate, and as of August 2008, I believe that there's no syntax for simply doing an outer join without editing config files.

Suppose I've got two tables, A and B, both of which are properly mapped in Hibernate, and I want to do an outer join on A.x and B.y. I'd write this:

List list=
session.createSQLQuery(
" select {a.*}, {b.*} " +
" from A as a " +
" left outer join B as b " +
" on (a.x = b.y) " +
" where a.x = b.y "
).addEntity("a", A.class).
addEntity("b", B.class).list();

Note that if there is no corresponding entry in B for an entry in A, Hibernate correctly gives you back null (i.e. it doesn't give you an instance of class B with all the fields set to null or default, you legitimately get back null in row[1] of that entry in list).

The {a.*} syntax is a placeholder and the addEntity() calls fill in the fields based on the mappings in Hibernate. This syntax is kind of awesome because I can write SQL queries but take advantage of a lot of the automation and simplification that Hibernate provides. And I can do this without actually understanding a lot of the more complex aspects of Hibernate's config files (not great in the long-run, of course, but great today!)

No comments: