sikrip
sikrip

Reputation: 681

Grails/Groovy: Modify a "query" closure at runtime

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!

Upvotes: 1

Views: 1429

Answers (1)

Arturo Herrero
Arturo Herrero

Reputation: 13140

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)

Upvotes: 2

Related Questions