【发布时间】:2011-08-21 00:20:24
【问题描述】:
我对嵌套域类有一个内部要求,我希望将父关系的更新传播给子级。一个代码示例可能会清楚:
class Milestone {
static belongsTo = [project:Project]
static hasMany = [goals:OrgGoals, children:Milestone]
String name
Date start
Date estimatedEnd
Date achievedEnd
...
}
当父里程碑的估计结束更新时,我希望子里程碑的估计自动更新相同的数量。 GORM's beforeUpdate() hook 似乎是一个合乎逻辑的地方:
为了让生活更轻松,我想使用一些simple Date arithmetic,所以我在 Milestone 类中添加了以下方法:
def beforeUpdate()
{
// check if an actual change has been made and the estimated end has been changed
if(this.isDirty() && this.getDirtyPropertyNames().contains("estimatedEnd"))
{
updateChildEstimates(this.estimatedEnd,this.getPersistentValue("estimatedEnd"))
}
}
private void updateChildEstimates(Date newEstimate, Date original)
{
def difference = newEstimate - original
if(difference > 0)
{
children.each{ it.estimatedEnd+= difference }
}
}
没有编译错误。但是当我运行以下集成测试时:
void testCascadingUpdate() {
def milestone1 = new Milestone(name:'test Parent milestone',
estimatedEnd: new Date()+ 10,
)
def milestone2 = new Milestone(name:'test child milestone',
estimatedEnd: new Date()+ 20,
)
milestone1.addToChildren(milestone2)
milestone1.save()
milestone1.estimatedEnd += 10
milestone1.save()
assert milestone1.estimatedEnd != milestone2.estimatedEnd
assert milestone2.estimatedEnd == (milestone1.estimatedEnd + 10)
}
我明白了:
Unit Test Results.
Designed for use with JUnit and Ant.
All Failures
Class Name Status Type Time(s)
MilestoneIntegrationTests testCascadingUpdate Failure Assertion failed: assert milestone2.estimatedEnd == (milestone1.estimatedEnd + 10) | | | | | | | | | | | Mon Jun 06 22:11:19 MST 2011 | | | | Fri May 27 22:11:19 MST 2011 | | | test Parent milestone | | false | Fri May 27 22:11:19 MST 2011 test child milestone
junit.framework.AssertionFailedError: Assertion failed:
assert milestone2.estimatedEnd == (milestone1.estimatedEnd + 10)
| | | | | |
| | | | | Mon Jun 06 22:11:19 MST 2011
| | | | Fri May 27 22:11:19 MST 2011
| | | test Parent milestone
| | false
| Fri May 27 22:11:19 MST 2011
test child milestone
at testCascadingUpdate(MilestoneIntegrationTests.groovy:43)
0.295
这表明 beforeUpdate 没有触发并做我想做的事。有什么想法吗?
【问题讨论】:
-
为什么不使用
estimatedEndsetter? -
我怀疑 GORM 事件可能不会在测试期间执行
-
@Victor:好点。我什至没有想到这一点,但这更有意义。 @Don:我相信它们不会在单元测试之后执行,但它们会在集成测试中针对完整的数据库运行。
-
当然。这显然是一个领域逻辑,而不是一些持久性基础设施。
标签: hibernate grails grails-orm grails-domain-class