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!

Answers


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)

Need Your Help

Root element not well-formed: extra tag being added on save

android xml

I'm totally new to this, and I follow the guide from this page, http://developer.android.com/training/basics/firstapp/building-ui.html

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.