我想将我的域类保存到数据库,而不指定createdUser
或createdDate
。我创建了一个名为AuditingInfo
的对象,并将其嵌入到主Person
域类中,如下所示:
AuditingInfo.groovy
:
class AuditingInfo {
static constraints = {
createdUser (nullable : true)
updatedUser (nullable : true)
createdDate(nullable : true)
updatedDate(nullable : true)
}
static mapping = {
columns {
createdUsercolumn: 'T_CREATED_USER'
updatedUsercolumn: 'T_UPDATED_USER'
createdDatecolumn: 'T_CREATED_DATE'
updatedDatecolumn: 'T_UPDATED_USER'
}
}
User createdUser
User updatedUser
Date createdDate
Date updatedDate
}
Person.groovy
:
class Person {
static embedded = ['auditingInfo']
AuditingInfo auditingInfo
static constraints = { auditingInfo(nullable: true) }
String name
Long id
}
我无法使用beforeInsert
域或beforeUpdate
类中的Person
和AuditingInfo
个事件,因为它始终会导致NullPointerException
org.grails.datastore.mapping.engine.event.AbstractPersistenceEventListener
}。
因此,我想使用metaClass
方式,如下所示(此操作在*GrailsPlugin.groovy
文件中定义,但不幸的是我的项目是Grails项目,而不是Grails插件项目):
def doWithDynamicMethods = { ctx ->
application.domainClasses.each { org.codehaus.groovy.grails.commons.GrailsDomainClass gc ->
gc.metaClass.beforeInsert = {
}
gc.metaClass.beforeUpdate = {
}
}
}
如何将此方法应用于我的项目上下文?非常感谢你。
答案 0 :(得分:3)
您可以在启动时执行的Bootstrap.groovy中应用metaClass修改。
答案 1 :(得分:2)
同意doelleri
只需添加您的代码:
application.domainClasses.each { org.codehaus.groovy.grails.commons.GrailsDomainClass gc ->
gc.metaClass.beforeInsert = {
}
gc.metaClass.beforeUpdate = {
}
}
进入BootStrap.groovy