【问题标题】:Grails/Groovy: Modify a "query" closure at runtimeGrails/Groovy:在运行时修改“查询”闭包
【发布时间】:2012-05-02 20:02:35
【问题描述】:

在 gorm 领域类中,我可以做到

def q = {
  property1{
    eq('attr', 0)
  }
}

MyDomainClass.list(q)

如何在运行时修改闭包“q”(或创建一个包含闭包“q”的限制的新闭包),例如我可以添加另一个属性限制?


更多详情

实际上我的问题是如何在域类层次结构中创建组合标准。

class Parent{
  int pAttr

  static def getCriteria(){
    def dummyParentCriteria = {
      eq('pAttr', 0)
    }
  }
}

class Child extends Parent{
  int cAttr

  static def getCriteria(){
    def dummyChildCriteria = {
      // (1) 
      eq('cAttr', 0)
    }
  }
}

在“dummyChildCriteria”中我想避免重复父母的限制。

我想以某种方式将 Parent 的 getCriteria 的结果合并到那里 (1)


命名查询继承的解决方案

class Parent{
  int pAttr
  static namedQueries = {
     parentCriteria{
       eq('pAttr', 0)
     }
  }
}

class Child extends Parent {
  int cAttr
  static namedQueries = {
     childCriteria{
       parentCriteria() 
       eq('cAttr', 0)
     }
  }
}

但如果有人知道最初问题的答案,那就太好了!

【问题讨论】:

    标签: grails groovy grails-orm criteria


    【解决方案1】:

    从 Grails 2.0.x 开始,您可以使用 Detached Criteria queries,它有很多用途,包括允许您创建常见的可重用条件查询、执行子查询和执行批量更新/删除。

    借助 Detached Criteria,您可以使用 Where Queries 进行查询组合。

    def parentCriteria = {
        pAttr == 0
    }
    
    def childCriteria = {
        cAttr == 0
    }
    
    def parentQuery = Parent.where(parentCriteria)
    def childQuery = Child.where(parentCriteria && childCriteria)
    

    【讨论】:

    • 已尝试分离标准,但我无法弄清楚如何有条件地添加标准。例如在条件闭包中我可以有: parentCriteria{qc-> if(qc.a1){eq('a1', qc.a1)} if(qc.a1){eq('a2', qc.a2) } /*等等...*/}。这可以用独立的标准来完成吗?
    猜你喜欢
    • 1970-01-01
    • 2011-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多