Extending domain class with one-to-many relationship in Grails

1.5k views Asked by At

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?

1

There are 1 answers

0
Emmanuel Rosa On

The short answer is you've got it right. Probably. The question to ask is whether you're ok with allowing the properties you've added to your subclasses to be set to NULL. I don't see a problem with what you have. You can learn more about Grails domain class inheritance and polymorphic queries from the Grails documentation and from my blog article on the subject.

If you're curious about the impact of your domain class model on the database, you can take a look at the queries GORM/Hibernate is running by logging then. I believe this is the article I've used to set up logging.