在 Grails 中使用 Hibernate HQL 命名查询?

2023-12-08

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

我一直在阅读有关他们的文章《利用 Hibernate》书籍,并且想知道是否有办法在 Grails 中使用它们。

命名查询与类映射一起包含在<class-name>.hbm.xml映射文件如下:

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

现在我确信<class-name>.hbm.xml 休眠映射文件可以包含并集成到 Grails GORM 配置中,如下所示这里有说明hibernate.cfg.xml其中包括休眠映射文件可以在 Grails 中使用。

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

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

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

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

我问的原因是我希望能够使用旧数据库并将其映射到一些对象以在 Grails 中使用,并将命名查询与映射一起存储。


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

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

或者更紧凑地使用方法链:

SomeDomainClass.withSession { session ->
   session.getNamedQuery('com.oreilly.hh.tracksNoLongerThan')
      .setTime('length', length)
      .list()
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 Grails 中使用 Hibernate HQL 命名查询? 的相关文章

随机推荐