Saturday, February 7, 2009

GORM executeQuery problem

As far as You know executeQuery method allows the execution of HQL queries against a domain class. I never tried it before cause used dynamic finders instead. But when I first tried to execute simple HQL query:
DocumentRevision.executeQuery("select max(dr.versionNumber) from DocumentRevision dr")
I've got an exception:
Caused by: org.hibernate.hql.ast.QuerySyntaxException: DocumentRevision is not mapped.
That was quiet surprised for me cause DocumentRevision domain class is mapped and I could perform all CRUD operations with it.

Reason for that exception was
there is one somewhat frustrating difference between GORM and Hibernate default behaviors. By default in Hibernate the short class name is used and as long as the domain short class name is unique then this is fine. So in my case I should include DocumentRevision with whole package name:
DocumentRevision.executeQuery("select max(dr.versionNumber) from com.myorg.myproject.core.domain.DocumentRevision dr")
But the easiest way I discovered of to work around this is to use a couple of Groovy shortcuts:
DocumentRevision.executeQuery("select max(dr.versionNumber) from ${DocumentRevision.name} dr")
"$DocumentRevision.name" is the equivalent of "DocumentRevision.class.getName()". It's not much longer than what I originally tried, so I stopped research on mentioned solution.

3 comments:

  1. Are you using 1.0.x? In 1.1 it was changed (finally) so you don't have to specify the full class name: http://jira.codehaus.org/browse/GRAILS-2596

    ReplyDelete
  2. Yes, this post is related to Grails 1.0.4.

    ReplyDelete
  3. this should work well with newer Grails versions

    ReplyDelete