【问题标题】:constructing Grails/Groovy where query in run-time在运行时构建 Grails/Groovy where 查询
【发布时间】:2013-11-18 19:53:59
【问题描述】:

是否可以在运行时在 grails/groovy 中构造这样的查询?

假设我有:

def query = Person.where {
     age in 18..65
}

在运行时我想给它增加权重:

def query = Person.where {
     age in 18..65
     weight in 100..200
}

可能吗?

【问题讨论】:

    标签: grails groovy grails-orm where-clause


    【解决方案1】:

    我会改用Criteria Queries。它们允许您非常轻松地动态构建您想要的查询。例如,您可以创建如下条件:

    def result = Person.createCriteria {
        'in'("age", [18..65])
    
        if (params.includeWeight) {
            'in'("weight", [100..200])
        }
    }.list()
    

    【讨论】:

      【解决方案2】:

      Person.where 是一个将Closure 作为参数的方法。闭包的一个特性是组合。以下是来自Groovy Goodness 的示例:

      def convert = { new Expando(language: it) }
      
      def upper = { it.toUpperCase() }
      
      // Composition.
      def upperConvert = convert << upper
      

      所以你可以这样做:

      def defaultWhere = {
        age in 18..65
      }
      
      if(someRuntimeTest) {
        defaultWhere << {
          weight in 100..200
        }
      }
      
      Person.where(defaultWhere)
      

      【讨论】:

      • 假设我从数据库中读取了一个属性列表并将它们放在一个列表 中,然后我可以将它插入到这个闭包中来构造它吗?示例:我的列表有“100...200 中的重量”、“100..190 中的高度”、“color=blue”?
      • hmmm 如果这个过滤器是字符串,你可能需要评估它。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-28
      • 2014-09-23
      • 2023-01-18
      相关资源
      最近更新 更多