grails:mastering_domain.createcriteria

mastering_Domain.createCriteria()

We usually put createCriteria() within a Grails services. In Grails, createCriteria() come with any domain object, and it return a type BuildableCriteria. Most often, we call its list() method to return a list of that domain object. Here is a code copy from the Grails document site:

def c = Account.createCriteria()
def results = c.list {
    like("holderFirstName", "Fred%")
    and {
        between("balance", 500, 1000)
        eq("branch", "London")
    }
    maxResults(10)
    order("holderLastName", "desc")
}

We put the query inside list{…}. In this example, the result would be a List<Account> that has holderFirstName like Fred%, with 500< balance < 1000, and the list will order by holderLastName in descending fashion.

It has 4 methods list, get, scroll,listDistinct. The mostly use ones are list, and get. The method get get one record, and the list method get a list of the related domain object.

Criterion Method are those method that we put inside the {…} to query the data source. The following list is copy from http://docs.grails.org/3.1.1/ref/Domain%20Classes/createCriteria.html. Should go there to see for details. The common ones would be eq, like, ilike, gt, ge, …

between("balance", 500, 1000)
eq("branch", "London")
eq("branch", "london", [ignoreCase: true])
eqProperty("lastTx", "firstTx")
gt("balance",1000)
gtProperty("balance", "overdraft")
ge("balance", 1000)
geProperty("balance", "overdraft")
idEq(1)
ilike("holderFirstName", "Steph%")
'in'("age",[18..65]) or not {'in'("age",[18..65])}
isEmpty("transactions")
isNotEmpty("transactions")
isNull("holderGender")
isNotNull("holderGender")
lt("balance", 1000)
ltProperty("balance", "overdraft")
le("balance", 1000)
leProperty("balance", "overdraft")
like("holderFirstName", "Steph%")
ne("branch", "London")
neProperty("lastTx", "firstTx")
order("holderLastName", "desc")
rlike("holderFirstName", /Steph.+/)
sizeEq("transactions", 10)
sizeGt("transactions", 10)
sizeGe("transactions", 10)
sizeLt("transactions", 10)
sizeLe("transactions", 10)
sizeNe("transactions", 10)
order("age", "desc")
firstResult(20)
maxResults(10)
cache(boolean)
  • grails/mastering_domain.createcriteria.txt
  • Last modified: 2020/08/31 16:55
  • by chongtin