1

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!

sikrip
  • 671
  • 8
  • 10

1 Answers1

2

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)
Arturo Herrero
  • 12,772
  • 11
  • 42
  • 73
  • Have tried detached criteria but I could not figure out how to conditionally add criteria. For example in the criteria closure i can have: parentCriteria{qc-> if(qc.a1){eq('a1', qc.a1)} if(qc.a1){eq('a2', qc.a2)} /*etc...*/}. Can this be done with detached criteria? – sikrip May 04 '12 at 08:36