Would this be correct way to extend Grails parent and child classes?
Originally I thought that overriding hasMany and belongsTo properties, would be a good idea but that did not work so well as it introduced conflicting functionality so I dropped it from subclasses.
What I am trying to do here is to package shared code between multiple applications. I am starting with these two classes in my plugin.
class Purchase {
String firstName
String lastName
static mapping = {
tablePerHierarchy false
}
static hasMany = [items: PurchaseItem]
}
class PurchaseItem {
BigDecimal price
Integer qty
statiuc belongsTo = [purchase: Purchase]
static mapping = {
tablePerHierarchy false
}
}
The application specific classes have to extend both Purchase and PurchaseItem so I am implementing it like so, inheriting one-to-many relationship:
class Flight {
static hasMany = [purchases: TicketPurchase]
}
class TicketPurchase extends Purchase {
// some class specific properties
static belongsTo = [flight: Flight]
}
class TicketPurchaseItem extends PurchaseItem
Integer bagQty
static namedQueries = {
ticketPurchaseItemsWithBagsByFlight {flightInstance->
purchase {
flight {
eq 'id', flightInstance.id
}
}
gt 'bagQty', 0
}
}
}
The namedQuery in TicketPurchaseItem joins Purchase and Flight even though super class Purchase does not belongTo Flight, only subclass TicketPurchase does.
TicketPurchase ticketPurchase = new TicketPurchase()
ticketPurchase.addToItems(new TicketPurchaseItem(bagQty: 5)).save()
Flight flight = Flight.first()
flight.addToPurchases(ticketPurchase).save()
// this works
def ticketPurchaseItemList = TicketPurchaseItem.ticketPurchaseItemsWithBagsByFlight(flight)
This works with Grails but is it good design or is there a better way to deal with domain classes extending one-to-many relationships?