我有以下域类:
假期:
class Holiday {
String justification
User user
//static belongsTo = User
static constraints = {
}
}
用户:
class User {
String login
String password
static hasMany = [ holidays : Holiday ]
static constraints = {
}
}
我在
Holiday
和User
之间创建了一对多关系。请注意,我没有在belongsTo
类中包括Holiday
。现在,我编写了以下集成测试:void testWithoutBelongsTo() {
def user1 = new User(login:"anto", password:"secret")
user1.save()
def holiday1 = new Holiday(justification:"went to trip")
holiday1.save()
user1.addToHolidays(holiday1)
assertEquals 1, User.get(user1.id).holidays.size()
user1.delete()
assertFalse User.exists(user1.id)
assertFalse Holiday.exists(holiday1.id)
}
显然,在上述测试案例中,我仅删除了
user1
实例,但是当我使用assert语句运行时,我可以看到GORM也隐式删除了holiday1
。我的测试用例已经通过!即使我在belongsTo
类中没有给Holiday
关键字,这怎么可能发生?我正在使用Grails 1.3.7版。
最佳答案
holiday1
从未保存,因为它无法验证:user
属性既未设置也不能为空。
这是Holiday.groovy
中的代码应如下所示:
class Holiday {
String justification
User user
//static belongsTo = User
static constraints = {
user(nullable: true)
}
}
然后进行测试,并在
user
中正确设置属性holiday1
:void testWithoutBelongsTo()
{
def user1 = new User(login:"anto", password:"secret")
user1.save(failOnError: true)
def holiday1 = new Holiday(justification:"went to trip",
user: user1) // Set user properly
holiday1.save(failOnError: true)
user1.addToHolidays(holiday1)
assert 1, User.get(user1.id).holidays.size()
holiday1.user = null // Unset user as otherwise your DB
// won't be happy (foreign key missing)
user1.delete()
assert ! User.exists(user1.id)
assert Holiday.exists(holiday1.id)
}
为了快速消除测试中的验证错误,请始终使用
save(failOnError: true)
。如果您的对象未通过验证,它将引发异常。
关于grails - 即使我省略了EmiratesTo关键字,GORM为什么仍要执行级联删除?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8352237/