Mapping the result of a native SQL query to a Grails domain class collection
by oliver | January 18, 2010 | In Grails, Hibernate | No Comments
Today I could once again not find a proper way to express a query needed for my current Grails project in either Hibernate HQL nor the DSL based variant of Hibernate’s Criteria API.
While it is quite simple to run native SQL Queries in Grails Project using Spring’s NamedParameterJdbcTemplate I never had to actually Map the result of a native SQL back to one of my Grails Domain Classes. After a bit of fiddling around it turned out that everything becomes quite trivial once you get ahold of the Hibernate SessionFactory that is made available by Grails for each request.
Let’s pretend we have the following Grails domain class:
package com.acme.domain class Foo { String name } |
You would execute a native SQL Query that returns a List of Foo instances like this:
import com.acme.domain.* def sessionFactory sessionFactory = ctx.sessionFactory // this only necessary if your are working with the Grails console/shell def session = sessionFactory.currentSession def query = session.createSQLQuery("select f.* from Foo where f.id = :filter)) order by f.name"); query.addEntity(com.acme.domain.Foo.class); query.setInteger("filter", 88); query.list()*.name; |