I’m currently in the process of converting the data layer in a server-side Java service to use hibernate. It has a lot of weird joins in the SQL, so the simplest solution for those cases in the code is to use the native SQL passthrough feature of hibernate. Normally when you run

List data = session.createSQLQuery("select field1, field2 .....")

You get back a java.util.List populated with Object[]’s. You have to reference the individual columns by their index value in order to get data out of them. This has the side-effect that if your database tables every change or columns get re-ordered your code is hosed up and difficult to debug.

A better way I’ve found is to use

List data = session.createSQLQuery("select  field1, field2.....")

This has the effect of returning a List containing Map objects for each row. It then becomes a simple matter to retrieve data based on the column name. If columns ever get added or re-ordered in your table your code will continue working.

for (Object object : data)
Map row = (Map)object;
System.out.println(row.get("field1") + ", " + row.get("field2"));

Post to Twitter

Posted by Andrew, filed under Hibernate. Date: March 7, 2008, 8:34 pm | 5 Comments »