Skip to content

Commit

Permalink
Merge pull request #33 from grails/GRAILS-10129
Browse files Browse the repository at this point in the history
Add docs for auto timestamp disable functionality
  • Loading branch information
jameskleeh committed May 8, 2017
2 parents 3d8e425 + b9f23a6 commit 2783714
Showing 1 changed file with 30 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -353,3 +353,33 @@ class Person {
----

WARNING: If you have `nullable: false` constraints on either `dateCreated` or `lastUpdated`, your domain instances will fail validation - probably not what you want. Omit constraints from these properties unless you disable automatic timestamping.

It is also possible to disable the automatic timestamping temporarily. This is most typically done in the case of a test where you need to define values for the `dateCreated` or `lastUpdated` in the past. It may also be useful for importing old data from other systems where you would like to keep the current values of the timestamps.

Timestamps can be temporarily disabled for all domains, a specified list of domains, or a single domain. To get started, you need to get a reference to the `AutoTimestampEventListener`. If you already have access to the datastore, you can execute the `getAutoTimestampEventListener` method. You can also inject the bean that corresponds to your GORM implementation: `timestampInterceptor` for Hibernate, `mongoTimestampInterceptor` for MongoDB.

Once you have a reference to the event listener, you can execute `withoutDateCreated`, `withoutLastUpdated`, or `withoutTimestamps`. The `withoutTimestamps` method will temporarily disable both `dateCreated` and `lastUpdated`.

Example:

[source,groovy]
----
//Only the dateCreated property handling will be disabled for only the Foo domain
autoTimestampEventListener.withoutDateCreated(Foo) {
new Foo(dateCreated: new Date() - 1).save(flush: true)
}
//Only the lastUpdated property handling will be disabled for only the Foo and Bar domains
autoTimestampEventListener.withoutLastUpdated(Foo, Bar) {
new Foo(lastUpdated: new Date() - 1, bar: new Bar(lastUpdated: new Date() + 1)).save(flush: true)
}
//All timestamp property handling will be disabled for all domains
autoTimestampEventListener.withoutTimestamps {
new Foo(dateCreated: new Date() - 2, lastUpdated: new Date() - 1).save(flush: true)
new Bar(dateCreated: new Date() - 2, lastUpdated: new Date() - 1).save(flush: true)
new FooBar(dateCreated: new Date() - 2, lastUpdated: new Date() - 1).save(flush: true)
}
----

WARNING: Because the timestamp handling is only disabled for the duration of the closure, you must flush the session during the closure execution!

0 comments on commit 2783714

Please sign in to comment.