Criteria do grails

4

Somebody please tell me what this $ {result [0] [0]} means, why did they put two pair of brackets?

def criteria = Person.createCriteria()
def result = criteria.list {
projections {
    max('age')
    min('age')
  }
}
println "The maximum age is ${result[0][0]}"
println "The minimum age is ${result[0][1]}"
    
asked by anonymous 01.01.2016 / 21:21

1 answer

3

As the tutorial from which the code in question was copied, this example combines projections and aggregate functions .

Projections modify the return of the select clause, so it does not make sense to copy the result to the Person entity.

In the GORM documentation we find the following passage:

  

When multiple fields are specified in the projection, a list of values will be returned. Otherwise a single value will be returned.

Thinking about Java, this means that the function return will be List<Object[]> or List<Object> .

In the case of its function, the SELECT will be something more or less of the form:

SELECT max(age), min(age)
FROM Person;

That is, we know that the result must have only one row with two columns representing respectively the return of the two aggregate functions (maximum and minimum).

As indexes in Groovy start from scratch, we end up with something like this:

      COLUNA

L   *-----------------------------*
I   | indice  | 0       | 1       |
N   *---------*---------*---------*
H   | 0       | max(age)| min(age)|
A   *---------*---------*---------*

That is, result[0][0] , returns the maximum of the first column. Already result[0][1] returns the minimum of the second column. Both use only the first (and only) line.

In practice, however, it is difficult for anyone to propagate this tabular result to the upper layers. Usually the result of the query passes through a ResultTransformer or a transformation with collect , but this is a topic for another question.

    
01.01.2016 / 22:14