我有几个Grails 2.1域类,其中包括GORM自动管理的dateCreated
和lastUpdated
字段,例如:
class Person {
Date dateCreated
Date lastUpdated
String name
}
我希望Grails在运行时自动填写这些字段,但我也想创建一些测试数据,以便在其中手动定义这些日期的值。麻烦的是,即使我专门设置了这些字段,Grails也会使用拦截器自动设置这些值。
我看过this SO question,它描述了如何允许对
dateCreated
进行更改,但是我也需要更改lastUpdated
。这可能吗?
最佳答案
糟糕,我的错误是,另一个问题中的方法确实可行,但是有问题的实体分别保存在其他地方。似乎还需要显式的flush
才能使工作正常:
def withAutoTimestampSuppression(entity, closure) {
toggleAutoTimestamp(entity, false)
def result = closure()
toggleAutoTimestamp(entity, true)
result
}
def toggleAutoTimestamp(target, enabled) {
def applicationContext = (ServletContextHolder.getServletContext()
.getAttribute(ApplicationAttributes.APPLICATION_CONTEXT))
def closureInterceptor = applicationContext.getBean("eventTriggeringInterceptor")
def datastore = closureInterceptor.datastores.values().iterator().next()
def interceptor = datastore.getEventTriggeringInterceptor()
def listener = interceptor.findEventListener(target)
listener.shouldTimestamp = enabled
null
}
def createTestPerson() {
def luke = new Person(name: "Luke Skywalker")
withAutoTimestampSuppression(luke) {
def lastWeek = new Date().minus(7)
luke.dateCreated = lastWeek
luke.lastUpdated = lastWeek
luke.save(failOnError: true, flush: true)
}
}
关于grails - 是否仅对测试数据覆盖Grails dateCreated和lastUpdated?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13516251/