Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1
Chapter 9

[ 239 ]

The mapping closure is implemented in Grails in a fashion very similar to
constraints. The mapping closure is executed, having set its delegate to an instance
of HibernateMappingBuilder. Within the closure code for mapping, we can use any
of the built-in methods to control how mapping should occur, or we can name the
column field itself for more fine-grained control over the mapping of a column. To
apply a table-per-subclass strategy and turn on caching, we can add the following:


static mapping = {
tablePerSubclass = true
cache = true
}

Querying


We've already seen in the examples some basic querying with list() and get().
The list method can be used with a number of named parameters that gives us finer
control over the result set returned:


// list all customers
Customer.list().each {
println "${it.firstName} ${it.lastName}"
}
// List the first 10 customers
Customer.list(max:10).each {
println "${it.firstName} ${it.lastName}"
}
// List the next 10 customers
Customer.list(max:10, offset:10).each {
println "${it.firstName} ${it.lastName}"
}
// List all customers in descending order sorted by last name
Customer.list(sort:"lastName",order:"desc").each {
println "${it.firstName} ${it.lastName}"

We've seen the get() method in action, which uses the database ID to return an
object. We can also use the getAll() method when we want to return more than
one object, as long as we have the IDs that we need:


def customers = Customer.getAll(2, 4, 5, 7)
Free download pdf