Using Hibernate HQL Named Queries in Grails?

2019-02-19 00:30发布

问题:

Is there a way to use Hibernate Named Queries in Grails, using HQL?

I've been reading about them in the Harnessing Hibernate book, and wondered if there was a way to use them in Grails.

Named queries are included, along with the class mappings, in a <class-name>.hbm.xml mapping files like so:

<query name="com.oreilly.hh.tracksNoLongerThan">
   <![CDATA[
         from Track as track
           where track.playTime <= :length
     ]>
</query>

Now I'm certain that an <class-name>.hbm.xml hibernate mapping file can be included and integrated into the Grails GORM configuration as it is stated here that the hibernate.cfg.xml which includes the hibernate mapping file can used within Grails.

In old Hibernate and Java it can be accessed this way:

    ...
Query query = session.getNamedQuery(
                "com.oreilly.hh.tracksNoLongerThan");

query.setTime("length", length);
return query.list();
    ...

But, how can one access these HQL named queries from Grails?

The reason I ask is I'd like to be able to take a legacy database and map it to some objects for use in Grails, and store the named queries along with the mappings.

回答1:

The easiest way is with the withSession method on any domain class, e.g.

SomeDomainClass.withSession { session ->
   Query query = session.getNamedQuery('com.oreilly.hh.tracksNoLongerThan')
   query.setTime 'length', length
   query.list()
}

or more compactly using method chaining:

SomeDomainClass.withSession { session ->
   session.getNamedQuery('com.oreilly.hh.tracksNoLongerThan')
      .setTime('length', length)
      .list()
}