Wednesday 7 August 2013

Grails pitfalls: Inheriting a parent class doesn't mean a new table


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:

  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{ }

2 comments:

  1. One question about that (nice) approach:
    Is there a way to query on BaseEntity-Level, like BaseEntity.list() or BaseEntity.executeQuery() ?
    I could not get this work :-(

    Thanks in advance,
    Dirk

    ReplyDelete
  2. 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