Existing Groovy DSLs
[ 234 ]
To indicate the "has many" associations between Customer/Invoice and Invoice/
SalesOrder, we insert a static hasMany setting. We can also indicate ownership
by using the belongsTo setting. In the preceding example, a sales order line has
no relevance except on an invoice. We apply a belongsTo setting to bind it to the
invoice. The belongsTo setting will cause deletes to cascade when the owning
object is deleted. If an invoice is deleted, the delete will cascade to the sales order
lines. Invoice does not belong to Customer; so for auditing purposes, the invoice
object will not be automatically deleted even if the customer is removed.
From the Groovy DSL point of view, hasMany is just a static table containing a map
of IDs and Class objects. GORM can analyze this map at load time in order to create
the correct table mappings.
GORM will automatically take care of the mapping between the Customer, Invoice,
and SalesOrder classes by creating invoice_sales_order and customer_invoice
join tables.
Customer objects are linked to Invoice objects through the customer_invoice join
table. Invoices are linked to sales orders via the invoice_sales_order join
table, using foreign keys.
The hasMany setting is defined as a Map containing a key and class for each domain
object that is associated. For each hasMany key encountered on a domain class,
GORM will inject an addTo(key) method. This translates to an addToOrders
method, which is added to Invoice, as the key used was Orders and an
addToInvoices method is added to Customer. Invoking these methods will
automatically save an order or invoice in the database and also update the join
tables with the correct keys:
given:
def fred = new CustomerWithInvoices(firstName:"Fred",
lastName:"Flintstone")
fred.save(flush:true, failOnError: true)
expect:
CustomerWithInvoices.count() == 1
Invoice.count() == 0
SalesOrder.count() == 0
when:
def invoice = new Invoice()
invoice.addToOrders(new SalesOrder(sku:"productid01",
amount:1, price:1.00))
http://www.ebook3000.com