GORM 支持从抽象基类和具体持久化GORM实体的继承。例如:
class Content {
Stringauthor
}
class BlogEntry extends Content {
URL url
}
class Book extends Content {
StringISBN
}
class PodCast extends Content {
byte[]audioStream
}
在上面的例子中,我们拥有一个Content父类和继承该类的几个具有不同特性的子类。
注意事项
在数据库层 Grails 默认使用table-per-hierarchy 映射,如parent 类(Content) 和他的子类(BlogEntry,Book等), 共享同一个表和一个名叫class的鉴别列。
Table-per-hierarchy 映射有不好的一面, 就是你继承映射不能有非空属性。另一种方法是使用 table-per-subclass ,可以启用ORM DSL。
然而,过度使用继承和 table-per-subclass ,由于使用外连接查询,会使查询的性能变得很糟糕。通常我们建议,如果你打算使用继承,不要滥用他,不要让你的继承层次太深。
多态查询
继承的结果是你可以进行多态查询。例如在Content父类中使用list方法会返回所有子类的Content:
def content = Content.list()// list all blog entries, books and podcasts
content =Content.findAllByAuthor('Joe Bloggs') // find all by author
def podCasts = PodCast.list()// list only podcasts