Sometimes we need to audit our domain classes. And sometimes you open a couple of classes and realize auditing fields have been copied in every class:
As you may imagine, this could improve a lot. But most of newbies don't want to create a new class and make the previous classes inherit from it because they think they will be creating a new table.
But... Did you know you can inherit from a class without creating a new table?
class Product{ Date dateCreated Date lastUpdated } class Category{ Date dateCreated Date lastUpdated }
As you may imagine, this could improve a lot. But most of newbies don't want to create a new class and make the previous classes inherit from it because they think they will be creating a new table.
But... Did you know you can inherit from a class without creating a new table?
The solution is really simple, the parent class should be in src/groovy and it should be an abstract class. Then you can extend that class. The child class will have all the parent's fields but without the penalty of having a new table.
// src/main/groovy/myapp/BaseEntity.groovy abstract class BaseEntity{ Date dateCreated Date lastUpdated } // grails-app/domain/myapp/Product.groovy class Product extends BaseEntity { } // grails-app/domain/myapp/Category.groovy class Category extends BaseEntity{ }
One question about that (nice) approach:
ReplyDeleteIs there a way to query on BaseEntity-Level, like BaseEntity.list() or BaseEntity.executeQuery() ?
I could not get this work :-(
Thanks in advance,
Dirk
Nop I'm afraid you can't. Making it abstract means you've decided not to include BaseEntity among the entities 'managed' by GORM. It only helps us not repeating BaseEntity fields in its children, just that.
ReplyDelete