Criteria of the grails

Asked

Viewed 110 times

4

Someone please tell me what this ${result[0][0]} means because 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]}"

1 answer

3


In accordance with 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 that it makes no sense to copy the result to the entity Person.

In the documentation of the GORM 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 of Java, this means that the return of the function will be a List<Object[]> or List<Object>.

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

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

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

Since Groovy ratings 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 to say, 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) row.

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.