Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between withCriteria and CreateCriteria in Grails?

Tags:

grails

What is their difference and why and where we need to use them,i think it seems like they have no difference at all to me ?

like image 799
Daniel Adenew Avatar asked May 24 '13 06:05

Daniel Adenew


3 Answers

withCriteria { ... } is essentially shorthand for createCriteria().list { ... }. If you need to use any of the other criteria methods (get, count, ...) or pass pagination parameters to list then you have to use the long-hand form.

SomeDomain.createCriteria().list(max:10, offset:50) {
  // ...
}
like image 160
Ian Roberts Avatar answered Nov 07 '22 00:11

Ian Roberts


It's worth adding what I just came across in the grails documentation for createCriteria().

Because that query includes pagination parameters (max and offset), this will return a PagedResultList which has a getTotalCount() method to return the total number of matching records for pagination. Two queries are still run, but they are run for you and the results and total count are combined in the PagedResultList.

Source

This means you can use getTotalCount() without having to initiate the call (it's made for you). This is very helpful. The example documentation shows:

def c = Account.createCriteria()
def results = c.list (max: 10, offset: 10) {
    like("holderFirstName", "Fred%")
    and {
        between("balance", 500, 1000)
        eq("branch", "London")
    }
    order("holderLastName", "desc")
}
println "Rendering ${results.size()} Accounts of ${results.totalCount}"

This capability is not available when using withCriteria().

like image 9
mnd Avatar answered Nov 07 '22 00:11

mnd


Example of createCriteria():

def criteria = OfferCredit.createCriteria {
    offer {
        eq('status', LeverageUtils.ACTIVE_STATUS)
        ge('expirationDate', new Date())
    }
    user {
        eq('userId', userId)
    }
    eq('status', LeverageUtils.ACTIVE_STATUS)
    order('creationDate', 'asc')
}

criteria.list()

Example of withCriteria():

List<Supermarket> results = Supermarket.withCriteria {
    like("sp_street", params.street)
    productSupermarket {
         product {
            idEq(params.product)
        }
        // or just eq('product', someProduct)
    }
    maxResults(10)
}
like image 5
biniam Avatar answered Nov 07 '22 00:11

biniam