设置Grails域类中日期字段的默认值
我正在尝试为域类中的设置Grails域类中日期字段的默认值,grails,grails-domain-class,Grails,Grails Domain Class,我正在尝试为域类中的Date字段设置默认值 我可以在mapping配置中使用defaultValue,但它不适用于Date字段(我在String和Integer上试过,效果很好) 这是一个例子: class Something { Date myField static mapping = { myField defaultValue: new Date() } } 此代码失败,因为Hibernate生成的CREATE语句不正确。有点像: ...
Date
字段设置默认值
我可以在mapping
配置中使用defaultValue
,但它不适用于Date
字段(我在String
和Integer
上试过,效果很好)
这是一个例子:
class Something {
Date myField
static mapping = {
myField defaultValue: new Date()
}
}
此代码失败,因为Hibernate生成的CREATE语句不正确。有点像:
... my_field datetime default Mon Nov 25 17:59:08 UYST 2013 not null ...
始终可以在静态初始值设定项中初始化字段,或在构造函数中设置值:
class Something {
// initializer
Date myField = new Date()
// or in the ctor
Something() {
myField = new Date()
}
}
这并没有在数据库模式中设置默认值,它只是在创建实例时设置字段的值。如果希望架构具有默认值,可以使用“defaultValue”映射项,如下所示:
class Something {
Date myField
static mapping = {
myField defaultValue: "now()"
}
}
为默认值设置的值取决于数据库供应商。(注意使用sql
now()
方法,而不是Java/Groovynew Date()
GORM很容易满足最基本的Date
用例;创建和更新
只需在域的属性中包含关键字dateCreated
和lastUpdated
,即可实现默认功能
警告:如果它们的约束可为null:false
则会导致失败。请删除这些约束或将autoTimestamp
设置为false
例如:
class MyDomain {
Date dateCreated
Date lastUpdated
Date yesterday = new Date().previous()
Date weekAgo = new Date() - 7
Date monthAgo = new Date() - 30
Date usaIndepenceDay = new Date().copyWith(
year: 1776,
month: Calendar.JULY,
dayOfMonth: 4,
hourOfDay: 0,
minute: 0,
second: 0)
static mapping = {
//autoTimestamp false
}
static constraints = {
//dateCreated nullable: false
}
}
阅读有关groovy日期的更多信息,请访问SO answer、the和GORM的日期事件功能您可以将其用于从系统日期自动获取默认板条箱日期
class User {
String userName
String firstName
String lastName
Date createdDate = new Date() // set system date
static mapping = {
version false
id generator: 'increment'
cache true
}
static constraints = {
userName(unique: true)
}
}
谢谢!我以为这就是解决方案,但不想要像now()那样的特定于数据库引擎的函数谢谢,我已经知道dateCreated和LastUpdate字段,但这些与我最初的问题无关:DI松散地将它们放在那里,因为我找不到关于grails日期的好的和快速的答案,并添加了一些易于理解的内容。我如何将默认日期设置为明天的日期?或者说从现在起四天?