Search code examples
grailsinheritancegrails-orm

Grails GORM Inheritance best practices


I am working on a grails project with potentially 36 domain classes each with a dozen plus unique properties and a handful of shared properties that can be inherited from a base domain class. The problem with this is that grails will generate 1 table with all the properties from all the domain classes that inherit from the base class. This means a table with well over 300 columns which seems problematic on multiple levels. The other route is to do away with inheritance and each domain represents a unique database table. No matter what, either a lot of time will be spent duplicating code or trying to manage the generated database. Is there another option that I am missing?

All thoughts and opinions welcome.


Solution

  • It would appear you are missing the all important tablePerHierarchy mapping value for domain classes. I highly recommend you read the Inheritance Strategies documentation regarding this.

    From the documentation:

    By default GORM classes use table-per-hierarchy inheritance mapping. This has the disadvantage that columns cannot have a NOT-NULL constraint applied to them at the database level. If you would prefer to use a table-per-subclass inheritance strategy you can do so as follows:

    class Payment {
        Integer amount
        static mapping = {
            tablePerHierarchy false
        }
    }
    
    class CreditCardPayment extends Payment {
        String cardNumber
    }
    

    The mapping of the root Payment class specifies that it will not be using table-per-hierarchy mapping for all child classes.