GORM Events
As of Grails 1.0, GORM supports the registration of events as closures that get fired when certain events occurs such as deletes, inserts and updates. To add an event simply register the relevant closure with your domain class.
Event types
The beforeInsert event
Fired before an object is saved to the db
class Person {
Date dateCreated
def beforeInsert = {
dateCreated = new Date()
}
}
The beforeUpdate event
Fired before an existing object is updated
class Person {
Date dateCreated
Date lastUpdated
def beforeInsert = {
dateCreated = new Date()
}
def beforeUpdate = {
lastUpdated = new Date()
}
}
You must still add a nullable:true constraint to both the dateCreated and lastUpdated properties to avoid validation exceptions.
The beforeDelete event
Fired before an object is deleted.
class Person {
String name
Date dateCreated
Date lastUpdated
def beforeDelete = {
new ActivityTrace(eventName:"Person Deleted",data:name).save()
}
}
The onLoad event
Fired when an object is loaded from the db:
class Person {
String name
Date dateCreated
Date lastUpdated
def onLoad = {
name = "I'm loaded"
}
}
Automatic timestamping
The examples above demonstrated using events to update a lastUpdated and dateCreated property to keep track of updates to objects. However, this is actually not necessary. By merely defining a lastUpdated and dateCreated property these will be automatically updated for you by GORM. (Note: As above, lastUpdated is not set upon object creation so you must also add a nullable : true constraint for lastUpdated.)
If this is not the behaviour you want you can disable this feature with:
class Person {
Date dateCreated
Date lastUpdated
static mapping = {
autoTimestamp false
}
}