user3074874
user3074874

Reputation: 95

Auto generated values in Grails domain class

Is there a way to add my own auto generated field to domain like id and version , If yes the please guide me . provide me URL form where i can read and under stand the core concept of Grails and Domain specific language .

Upvotes: 1

Views: 894

Answers (3)

Graeme Rocher
Graeme Rocher

Reputation: 7985

You would need to write an AST transform to inject the fields you want to add automatically. The one that injects ‘id’ and ‘version’ can be found here as an example:

https://github.com/grails/grails-core/blob/master/grails-core/src/main/groovy/org/codehaus/groovy/grails/compiler/injection/DefaultGrailsDomainClassInjector.java

You would then need to write a GORM event listener to automatically update the values of these properties. See

https://github.com/grails/grails-data-mapping/blob/master/grails-datastore-gorm/src/main/groovy/org/grails/datastore/gorm/events/AutoTimestampEventListener.java

For an example of the one that updates the dateCreated/lastUpdated properties.

These can both be written in a separate Gradle/Maven project which you then reference in the dependencies of your BuildConfig.groovy file.

Upvotes: 1

dmahapatro
dmahapatro

Reputation: 50265

use install-template in the app to get all default templates:

grails install-template

after which you would be able to see /src/templates (newly created)

Modify DomainClass.groovy under /src/templates/artifacts as below:

@artifact.package@class @artifact.name@ {

    //according to your need
    Long myId
    Integer myVersion

    static constraints = {
    }
}

Done!!!!

Henceforth, when create-domain-class command is used to create a domain class, those fields will be auto populated.

Upvotes: 7

Nathan
Nathan

Reputation: 3200

I am not sure I am understanding your question correctly but here is the link to the web features of Grails documentation. The "Link Generation API" may be something you are asking after.

If you would like to manage ID and version than using Spring Security (plugin or full docs) or SQL features may be the direction you want to read more about.

EDIT: Try this Stackoverflow question and answer on using inheritance. Seems to be very similar to what you are asking.

Upvotes: 1

Related Questions