简体   繁体   中英

And/Or query conditions in Criteria with Grails

I'm trying to query some data information from the DB using Hibernate Criteria, the query needs to check with the data obtained dynamically from the front-end, so I have to iterate a list and generate the and/or conditions when querying, but I'm not getting any results.

This is my actual closest approach:

if (params."chartsForm[tickets][]" != null) {
                    def tickets = params."chartsForm[tickets][]"
                    (and {
                        def ticket = tickets[0]
                        ilike("ticketCode", "$ticket%")

                        for (def i = 1; i < tickets.size(); i++) {
                            (or {
                                ticket = tickets[i]
                                ilike("ticketCode", "$ticket%")
                            })
                        }
                    })
                }

Anyone knows how to do this or what I'm missing?

Edited to add: I'm not addressing the general structure of your query or apparent problems with the logic or looping. Just addressing why the results don't appear to match what you expect. If this is the actual query you're using, and not just an example for StackOverflow, then... I dunno, lots of other suggestions.

It's not clear to me what your query is trying to find. But I think your or clause is in the wrong place. And it only has a single item in it, so it's doing nothing.

Given input

ticket[0]="fus"
ticket[1]="roh"
ticket[2]="dah"

Your query will end up being:

and {
  ilike("ticketCode", "fus%")
  ilike("ticketCode", "roh%")
  ilike("ticketCode", "dah%")
}

Which will return zero results because you're looking for three different values on the same field.

The and clause means everything in the block has to match. The nested or would be "and"ed with everything in the top level block.

Converting to SQL, this would look like:

WHERE ticketCode LIKE "fus%" AND (ticketCode LIKE "roh%" OR <some other statement if you added it>) AND (ticketCode LIKE "dah%" OR <...>)

Note that the or s are still part of the and s (I added the "extra stuff" for clarity since otherwise there would be no "OR" in the query)

Edit: More robust description

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM