Search code examples
grailsgrails-ormcriteria

Grails define criteria


How can I create(only define) a criteria only once where I have to bind multiple tables under a lot of conditions(so if I understand things right have to use withCriteria). And then execute the criteria later two times to get the results.

  1. First get the result from a list with offset and max values
  2. Get the whole count number

Please help I've tried multiple things but did't get it working...

I was trying something like this

def histories = TerminHistory.withCriteria{....} //only define it at this point

def historiesDisplay = histories.list(max: 10, offset: 10) //run it
def historiesCount = histories.count() //run it

Solution

  • You need DetachedCriteria for these kind of lazy operations. Sub querying the associations will again be detached.

    One form of detachedCriteria is using where. Look at wherQueries which works in the same way as detachedCriteria. Expanding your example:

    def histories = TerminHistory.where{....} //only defined it at this point
    //def histories = new DetachedCriteria(TerminHistory).build{....}
    
    def historiesDisplay = histories.list(max: 10, offset: 10) //run it
    def historiesCount = histories.count() //run it
    

    Note:-
    DetachedCriteria and Where queries are available from Grails 2.0 version and above.