开发者

Newbie question on grails "createCriteria"

开发者 https://www.devze.com 2023-03-10 06:55 出处:网络
I am new to Grails criteria builder, can someone please explain what does the following mean? def c = Account.createCriteria()

I am new to Grails criteria builder, can someone please explain what does the following mean?

def c = Account.createCriteria()
         def results = c {

             like("hold开发者_如何学CerFirstName", "Fred%")
             and {
                 between("balance", 500, 1000)
                 eq("branch", "London")
             }
             maxResults(10)
             order("holderLastName", "desc")
         }

Does it mean

  • Select * from account where holderFirstName like 'fred%' and (balance between 500 and 1000 **and** branch='london')
  • Select * from account where holderFirstName like 'fred%' and (balance between 500 and 1000 **or** branch='london')

If i want to use "or" and "and" together how do I do that?


Your example would execute as:

select * from account 
where holderFirstName like 'Fred%' 
and balance between 500 and 1000 
and branch = 'London'

All top level conditions are implied to be AND'ed together. You could create the same Criteria as:

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

To get your second query use this Criteria:

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

Nest your and / or closures for more complex Criteria.


Your current criteria means "and" in the two conditions of balance and branch. so

Select * from account where holderFirstName like 'fred%' and (balance between 500 and 1000 and branch='london') is correct, just that it will hold maximum 10 results and will be sorted on the basis of "holderLastName" in descending order.

To use and and or together you also need to specify an or block in criteria, so your criteria will look something like

Account.createCriteria()
         def results = c {

             like("holderFirstName", "Fred%")
             and {
                 between("balance", 500, 1000)
                 eq("branch", "London")
             }
             or{
                 eq("prop1", prop1)
                 eq("prop2",prop2)
             }
             maxResults(10)
             order("holderLastName", "desc")
         }

in this criteria there is an and between balance and branch conditions. and also an or between prop1 and prop2

0

精彩评论

暂无评论...
验证码 换一张
取 消