MappedSuperclass Alternatives in Grails

2020-02-11 11:37发布

In many past projects, I used this JPA / Hibernate approach to add auditing capabilities to a system. It's very effective and unobtrusive.

Is there a Grails @MappedSuperclass alternative (short of coding domain model objects in Java instead of Groovy)? How can one declare a parent class in a table-per-subclass approach without having a table created for it? I've read the GORM documentation (5.2.3 Inheritance in GORM) but besides the table-per-hierarchy vs. table-per-subclass discussion, I did not find any details on how to do this.

Alternatively, what is the recommended way to achieve this type of auditing in Grails?

1条回答
不美不萌又怎样
2楼-- · 2020-02-11 11:52

OK, did a little bit more searching and I answered my own question :)

Essentially, it's as simple as declaring the MappedSuperclass as abstract and grails will not create a table for it. I realized by re-reading the manual (RTFM basically...works wonders): "GORM supports inheritance both from abstract base classes and concrete persistent GORM entities." I.e. concrete classes are persistent, so abstract ones are not. Pays to read more carefully.

E.g.

abstract class Auditable {
    Date dateCreated
    Date lastUpdated
}

class Book extends Auditable {
    String title
    String description
}

Only the book table will be created and it will have the

date_created

and

last_updated

columns. Furthermore, as an added bonus, the dateCreated and lastUpdated properties are auto time-stamped by Grails.

Hope this helps others.

查看更多
登录 后发表回答