Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1
Chapter 9

[ 235 ]

invoice.addToOrders(new SalesOrder(sku:"productid02",
amount:3, price:1.50))
invoice.addToOrders(new SalesOrder(sku:"productid03",
amount:2, price:5.00))

then: "Invoice or sales orders are not yet persisted"
CustomerWithInvoices.count() == 1
Invoice.count() == 0
SalesOrder.count() == 0

when:
fred.addToInvoices(invoice)
fred.save(flush:true, failOnError: true)

then: "Saving cascades to invoice and sales orders"
CustomerWithInvoices.count() == 1
Invoice.count() == 1
SalesOrder.count() == 3

Many-to-many


Many-to-many associations are rarer than any of the other associations, and can be
tricky to model. In GORM, all we need to do is to make the association bi-directional
and give ownership to one side by applying a belongsTo setting. GORM will take
care of the rest.


A tunes database needs to model the fact that artistes perform on many songs but
also that artistes collaborate on songs, so songs can have many artistes. Modeling
this in GORM is the essence of simplicity:


class Artist {
String name
static hasMany = [songs:Song]
}

class Song {
String title
static belongsTo = Artist
static hasMany = [artists: Artist]
}
Free download pdf