Java Reference
In-Depth Information
Finally, the mapping block is used to customize how the class is mapped to a database
table. By default, Grails will generate a table whose name matches the class name. Because
the word order is an SQL keyword, the resulting DDL statement would have problems.
In the mapping block the generated table name is specified to be orders , rather than
order , to avoid that problem. Also, Hibernate treats all associations as lazy. In this case,
that means that if an order is loaded, a separate SQL query will be required to load the or-
der lines as well. In the mapping block, the fetch join relationship means that all the
associated order lines will be loaded at the same time as the order, via an inner join.
The OrderLine class contains the product being ordered and the quantity, as shown in
the following listing.
Listing 8.13. The OrderLine POGO, which is assembled to build an Order
class OrderLine {
Product product
int quantity
double getPrice() { quantity * product?.price }
static constraints = {
quantity min:0
}
}
The getPrice method multiplies the quantity times the price of the product to get the
price of the order line. This, in turn, is summed in order to get the total price, as you saw
earlier.
Note also that the OrderLine class does not have a reference to the Order it belongs
to. This is a unidirectional cascade-delete relationship. If the order is deleted, all the order
lines go, but you cannot navigate from an order line to its associated order.
When you declare a hasMany relationship, Grails then provides methods for adding the
contained objects to their containers. To illustrate one of those methods, here's the file
BootStrap.groovy , which is a configuration file used in a Grails application for ini-
tialization code. The next listing shows code that instantiates a customer, two products, an
order, and some order lines and saves them all to the database.
Search WWH ::




Custom Search