Setting default value for Date field in Grails Domain Class
grails, grails-domain-class
Solution
You can always initialize the field in the static initializer or set the value in the constructor:
class Something {
// initializer
Date myField = new Date()
// or in the ctor
Something() {
myField = new Date()
}
}
This doesn't set a default value in the database schema, it merely sets the value of the field on creation of the instance. If you want the schema to have a default value, you can use the 'defaultValue' mapping entry like so:
class Something {
Date myField
static mapping = {
myField defaultValue: "now()"
}
}
the value you set for the default value is dependent on your database vendor. (notice the use of sql `now()` method rather than Java/Groovy `new Date()`.
Problem
I'm trying to set a default value for a `Date` field in a Domain class. I can use `defaultValue` in the `mapping` configuration but it doesn't work with `Date` fields (I've tried it on `String` and `Integer` and it works fine). This is an example: ``` class Something { Date myField static mapping = { myField defaultValue: new Date() } } ``` This code fails because the CREATE statement that Hibernate generates is incorrect. It is something like: ``` ... my_field datetime default Mon Nov 25 17:59:08 UYST 2013 not null ... ```