我对嵌套域类有一个内部要求,我希望将父关系的更新传播给子级。一个代码示例可以清楚地说明:
class Milestone {
static belongsTo = [project:Project]
static hasMany = [goals:OrgGoals, children:Milestone]
String name
Date start
Date estimatedEnd
Date achievedEnd
...
}
当父里程碑的估计结束更新时,我希望孩子的估计自动更新相同的数量。GORM 的 beforeUpdate() 钩子似乎是这样做的合乎逻辑的地方:
为了让生活更轻松,我想使用一些简单的 Date 算术,所以我在 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 没有触发并做我想要的。有任何想法吗?