Grails/Groovy: Modify a “query” closure at runtime

耗尽温柔 提交于 2020-01-16 04:58:08

问题


In a gorm domain class, I can do

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

MyDomainClass.list(q)

How could I modify the closure 'q' (or create a new closure that would contain the restrictions that closure 'q' has) at runtime so for example I could add another property restriction?


More details

Actually my problem is how to create combined criteria in a Domain Class Hierarchy.

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

In 'dummyChildCriteria' I want to avoid repeating parent's restrictions.

I would like to somehow combine the result of Parent's getCriteria there (1)


A solution with named queries inheritance

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

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

But if someone knows the answer to the initial question it would be nice to know!


回答1:


Since Grails 2.0.x, you can use Detached Criteria queries that have many uses including allowing you to create common reusable criteria queries, execute subqueries and execute batch updates/deletes.

With Detached Criteria, you can use Where Queries doing query composition.

def parentCriteria = {
    pAttr == 0
}

def childCriteria = {
    cAttr == 0
}

def parentQuery = Parent.where(parentCriteria)
def childQuery = Child.where(parentCriteria && childCriteria)


来源:https://stackoverflow.com/questions/10420812/grails-groovy-modify-a-query-closure-at-runtime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!