GORM supports the registration of events as methods that get fired when certain events occurs such as deletes, inserts and updates. The following is a list of supported events:
beforeInsert
- Executed before an object is initially persisted to the database
beforeUpdate
- Executed before an object is updated
beforeDelete
- Executed before an object is deleted
afterInsert
- Executed after an object is persisted to the database
afterUpdate
- Executed after an object has been updated
afterDelete
- Executed after an object has been updated
onLoad
- Executed when an object is loaded from the database
To add an event simply register the relevant closure with your domain class.
Do not attempt to flush the session within an event (such as with obj.save(flush:true)). Since events are fired during flushing this will cause a StackOverflowError.
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()
}
}
The beforeDelete event
Fired before an object is deleted.
class Person {
String name
Date dateCreated
Date lastUpdated def beforeDelete() {
ActivityTrace.withNewSession {
new ActivityTrace(eventName:"Person Deleted",data:name).save()
}
}
}
Notice the usage of
withNewSession
method above. Since events are triggered whilst Hibernate is flushing using persistence methods like
save()
and
delete()
won't result in objects being saved unless you run your operations with a new
Session
.
Fortunately the
withNewSession
method allows you to share the same transactional JDBC connection even though you're using a different underlying
Session
.
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.
If this is not the behaviour you want you can disable this feature with:
class Person {
Date dateCreated
Date lastUpdated
static mapping = {
autoTimestamp false
}
}