在 Grails 中使用 Hibernate HQL 命名查询? [英] Using Hibernate HQL Named Queries in Grails?

查看:28
本文介绍了在 Grails 中使用 Hibernate HQL 命名查询?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在 Grails 中使用 Hibernate 命名查询,使用 HQL?

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

我一直在 Harnessing Hibernate 一本书中阅读有关它们的内容,我想知道是否有一种方法可以在 Grails 中使用它们.

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

命名查询与类映射一起包含在 .hbm.xml 映射文件中,如下所示:

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>

现在我确定 .hbm.xml hibernate 映射文件 可以作为 此处声明 hibernate.cfg.xml 包含可以在 Grails 中使用的 hibernate 映射文件.

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.

在旧的 Hibernate 和 Java 中,它可以通过这种方式访问​​:

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();
    ...

但是,如何从 Grails 访问这些 HQL 命名查询?

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

我问的原因是我希望能够采用旧数据库并将其映射到一些对象以在 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.

推荐答案

最简单的方法是在任何域类上使用 withSession 方法,例如

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()
}

这篇关于在 Grails 中使用 Hibernate HQL 命名查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆