7.2.3 Inheritance in GORM - Reference Documentation
Authors: Graeme Rocher, Peter Ledbrook, Marc Palmer, Jeff Brown, Luke Daley, Burt Beckwith, Lari Hotari
Version: 3.1.3
7.2.3 Inheritance in GORM
GORM supports inheritance both from abstract base classes and concrete persistent GORM entities. For example:class Content {
String author
}
class BlogEntry extends Content {
URL url
}
class Book extends Content { String ISBN }
class PodCast extends Content { byte[] audioStream }
Content
class and then various child classes with more specific behaviour.Considerations
At the database level Grails by default uses table-per-hierarchy mapping with a discriminator column calledclass
so the parent class (Content
) and its subclasses (BlogEntry
, Book
etc.), share the same table.Table-per-hierarchy mapping has a down side in that you cannot have non-nullable properties with inheritance mapping. An alternative is to use table-per-subclass which can be enabled with the ORM DSLHowever, excessive use of inheritance and table-per-subclass can result in poor query performance due to the use of outer join queries. In general our advice is if you're going to use inheritance, don't abuse it and don't make your inheritance hierarchy too deep.Polymorphic Queries
The upshot of inheritance is that you get the ability to polymorphically query. For example using the list method on theContent
super class will return all subclasses of Content
:def content = Content.list() // list all blog entries, books and podcasts content = Content.findAllByAuthor('Joe Bloggs') // find all by authordef podCasts = PodCast.list() // list only podcasts