How to get the value from sum() in a Grails criteria

2.2k views Asked by At

I can't use the + operator with resultado[0] + obj.nopersonas, nopersonas is an Integer.

fhinicio(blank:false, validator : { val, obj ->
    def diff = groovy.time.TimeCategory.minus(obj.fhfinal, val)
    def total = diff.hours*60 + diff.minutes
    if (total < 15){
        return "reserva.fhfinal.tiempo.min.label"
    } else {            
        if (total > 60) {
            return "reserva.fhfinal.tiempo.max.label"
        } else {
            def reserva = Reserva.createCriteria()
            def resultado = reserva.list() {
                or {
                    and {
                        ge('fhinicio', val)
                        le('fhinicio', obj.fhfinal)
                    }
                    and {
                        ge('fhfinal', val)
                        le('fhfinal', obj.fhfinal)
                    }
                }

                projections {
                    sum('nopersonas')
                }
            } 

            //this is not working   
            def aff = resultado[0] + obj.nopersonas

Cannot execute null+null. Stacktrace follows: Message: Cannot execute null+null

3

There are 3 answers

0
Emmanuel Rosa On

You've got a couple of problems to resolve:

  1. The criteria query is returning null
  2. obj.nopersonas is null

The criteria query

To fix the criteria query, start without the projection:

def reserva = Reserva.createCriteria()
def resultado = reserva.list {
    or {
        and {
            ge('fhinicio', val)
            le('fhinicio', obj.fhfinal)
        }
        and {
            ge('fhfinal', val)
            le('fhfinal', obj.fhfinal)
        }
    }
}

Make sure you're getting the appropriate instances of Reserva. Then, add the projection and since you're expecting a single value, use the get() method instead of list().

def reserva = Reserva.createCriteria()
def resultado = reserva.get {
    or {
        and {
            ge('fhinicio', val)
            le('fhinicio', obj.fhfinal)
        }
        and {
            ge('fhfinal', val)
            le('fhfinal', obj.fhfinal)
        }
    }

    projections {
        sum('nopersonas')
    }
} 

def aff = resultado + obj.nopersonas

obj.nopersonas

Since obj.nopersonas is null, I'm assuming the property is nullable. If the property is supposed to be nullable, then you'll need to account for that in your validator.

0
Juan Pérez On

It is working.

Integer variable_name = Integer.valueOf(resultado[0].toString())

0
Shashank Agrawal On

You can simply handle the null condition:

def aff = (resultado[0] ?: 0) + (obj.nopersonas ?: 0)