One-to-Many Domain Class Extension in Grails

Would this be the right way to extend the Grails parent and child classes?

Initially, I thought that overriding hasMany and belong to properties would be a good idea, but it did not work as well as it led to conflicting functionality, so I dropped it from subclasses.

What I'm trying to do here is batch shared code between multiple applications. I start 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 } } 

Application-specific classes should distribute both Purchase and PurchaseItem, so I implement it this way, inheriting a 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 named request in TicketPurchaseItem is attached to the purchase and flight, even if the superclass purchase does not belong to Flight, only the TicketPurchase subclass 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 a good design, or is there a better way to deal with one-to-many domain classes that extend?

+5
source share
1 answer

Short answer: everything is all right with you. Probably. The question is, do you agree that the properties you add to your subclasses are set to NULL. I do not see a problem with what you have. You can learn more about Grails class inheritance and polymorphic queries from the Grails documentation and from my blog article on this.

If you are interested in learning about the effect of a domain class model on a database, you can take a look at the queries that GORM / Hibernate runs by logging. I believe this is the article I used to configure logging.

0
source

All Articles