Including maximum and bias criteria within criteria GORMBuilder returns an error

Can I make this code shorter?

if(count == null && from = null) {
    creditAdviceList = CreditAdvice.findAll {
        ilike('id', "%$idFilter%")
        .....
        ilike('statusCode', statusCodeFilter)
    }
}
else if(count != null && from == null) {
    creditAdviceList = CreditAdvice.findAll(max: count) {
        ilike('id', "%$idFilter%")
        .....
        ilike('statusCode', statusCodeFilter)
    }
}
else if(count == null && from != null) {
    creditAdviceList = CreditAdvice.findAll(offset: from) {
        ilike('id', "%$idFilter%")
        .....
        ilike('statusCode', statusCodeFilter)
    }
}
else if(count != null && from != null) {
    creditAdviceList = CreditAdvice.findAll(max: count, offset: from) {
        ilike('id', "%$idFilter%")
        .....
        ilike('statusCode', statusCodeFilter)
    }
}

      

You see, this is a series statement if

for every possible scenario. Imagine that if the parameter is used order

and cache

is selected - it is basically 16 unique operators if

!

I tried this [more] shorter code:

creditAdviceList = CreditAdvice.findAll {
    ilike('id', "%$idFilter%")
    .....
    ilike('statusCode', statusCodeFilter)

    if(count != null) {
        maxResults(count)
    }
    if(from != null) {
        firstResult(from)
    }
}

      

But this gives me an error:

...No signature of method: grails.gorm.DetachedCriteria.maxResults() is applicable for argument types: (java.lang.Integer)...

I tried to convert offset

into int

, Integer

, String

etc. I also omit the operator if

inside the criteria, but the same error message appears.

+3


source to share


2 answers


findAll

with a closed closure uses internally DetachedCriteria

, which is not the same as the result you would get from the createCriteria

one mentioned in the docs. If groovy finds "something close", it will inform you in an error message. The easiest way to deal with your max / from requirements would be simply with a map (which is the first argument). For example:.

def qcfg = [:]
if (count) {
    qcfg.count = count
}
if (from) {
    qcfg.offset = from
}
creditAdviceList = CreditAdvice.findAll(qcfg) { ... }

      



mix, match, extract, cut as you like.

+2


source


As far as I can see, the only difference is the pagination options. If my eyes don't deceive me, yes, you can:

Map paginationArgs = [max: count, offset: from].findAll { 
   it.value != null 
}
List<CreditAdvice> creditAdviceList = CreditAdvice.findAll(paginationArgs) {
   ilike('id', "%$idFilter%")
   .....
   ilike('statusCode', statusCodeFilter)
}

      



You can style it differently, but in principle you can build the pagination arguments first and pass them to findAll

. Lack of duplicate code, clearer responsibility of conditions. To clarify, I add all the parameters and then filter them to exclude those that are null.

+1


source







All Articles