haedes
haedes

Reputation: 622

How to create a generic field like version in Grails?

I am creating a restful service from Grails and would like to add a user field on every table which on insert or on update automatically changed to the corresponding user making the change.

Is there any way to create a variable like version or dateCreated which are automatically bound to each domain where defined and added automatically updated on creation or update?

Upvotes: 0

Views: 212

Answers (1)

dsharew
dsharew

Reputation: 10665

1. Define an abstract domain class, put your common fields on it (on src/groovy)
2. Extend it by each domain object that needs the common fields

So your abstract domain class will look like this (also note how the updateByUser and createdByUser are automatically determined):

abstract class AbstractDomain  {

    transient securityService

    User createdByUser;
    User updatedByUser;

    def beforeInsert() {

        if(null != securityService) {

            User currentUser = securityService.getCurrentUser()

            if(null != currentUser){
                this.createdByUser = currentUser
            }
        }
    }

    def beforeUpdate() {

        if(null != securityService) {

            User currentUser = securityService.getCurrentUser()

            if(null != currentUser){
                this.updatedByUser = currentUser
            }
        }
    }
}

Upvotes: 1

Related Questions