是否有可能将命名查询元编程到grails域类上? [英] Is it possible to metaprogram named queries onto a grails domain class?

查看:80
本文介绍了是否有可能将命名查询元编程到grails域类上?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以将命名查询元编程到grails域类上?如果是这样,怎么样?

Is it possible to metaprogram named queries onto a grails domain class? If so, how?

谢谢

Thanks

推荐答案

namedQueries 属性,您可以使用它来添加自己的命名查询。如果你想在插件中使用元编程(而不是直接编辑域类)来实现这一点,你应该在

Domain classes have a namedQueries property that you can use to add your own named queries. If you want to do this using metaprogramming from within a plugin (rather than by editing the domain class directly), you should do it in the doWithDynamicMethods closure of the plugin's descriptor file.

类似这样的东西应该可以工作:

Something like this should work:

class MyPlugin {

  def doWithDynamicMethods = { applicationContext ->

    application.domainClasses.each { domainClass -> 

      boolean domainClassFilter = domainClass as Boolean

      if (domainClassFilter) {
        domainClass.metaClass.static.myNamedQuery = {->  

          // implementation of your named query goes here. Here is an example implementation
          // that returns all instances with status == 'ready'
          String simpleClassName = domainClass.simpleName
          domainClass.findAll("from $simpleClassName where status = ?", ['ready'])
        } 
      }
    } 
  } 
}

这会将 myNamedQuery 添加到安装插件的应用程序中的每个域类。如果您只想将其添加到某些域类,然后用更合适的测试替换 domainClassFilter 的值。

This will add myNamedQuery to every domain class in the application that the plugin is installed in. If you only want to add it to some domain classes, then replace the value of domainClassFilter with a more appropriate test.

这篇关于是否有可能将命名查询元编程到grails域类上?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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