【发布时间】:2015-03-20 22:22:37
【问题描述】:
我正在尝试了解 GORM 的级联删除。这是没有任何修饰符的默认 GORM 行为。我知道如果域类Owner 的拥有实例拥有Owned 域类的多个实例,那么当Owner 实例被删除时,所有拥有的实例也将被删除。但是,如果拥有的实例同时由两个不同的 Owners 拥有,并且只有一个 Owner 被删除,该怎么办。拥有的实例是否会因为仍由另一个未删除的所有者拥有而不会被删除?
编辑:我实际上尝试进行实验(至少是第一部分),但没有达到预期的结果。作为一个新手,我很确定我做错了什么。就是不知道是什么。
class MainController {
def index() {
// creating a few instances of the owned domain class
def owneda = new Owned(name: 'Owned A')
def ownedb = new Owned(name: 'Owned B')
def ownedc = new Owned(name: 'Owned C')
// now we make these instances belong to an instance of OwnerA
// first we create an instance of OwnerA
def ownerA = new OwnerA(name: 'Owner A')
// then we give it ownership of all the instances of Owned that we created
ownerA.addToOwned(owneda)
ownerA.addToOwned(ownedb)
ownerA.addToOwned(ownedc)
// now we save the owner instance
ownerA.save(flush: true)
// now we see how many instances of both Owners and Owned are in our db
println "The number of Owner As in existence are: " + OwnerA.count()
println "The number of Owned in existence are: " + Owned.count()
// Now we delete the owner instance
ownerA.delete(flush: true)
// now we see how many instances of both Owners and Owned are in our db after the deletion
println "After deletion of the OwnerA instance..."
println "The number of Owner As in existence are: " + OwnerA.count()
println "The number of Owned in existence are: " + Owned.count()
}
}
我确实将 belongsTo 放在了我的 Owned 类中,并将 hasMany 放在了我的 Owner 类中。
输出:
...........The number of Owner As in existence are: 0
The number of Owned in existence are: 0
After deletion of the OwnerA instance...
The number of Owner As in existence are: 0
The number of Owned in existence are: 0
【问题讨论】:
-
你试过了吗?您是否观察到默认行为是什么? ;)
-
@JoshuaMoore 不,我没有。听起来像是即将到来的周末的一个有趣的项目。我必须尝试一下并对 GORM 进行一些研究。
-
@JoshuaMoore 如果您仍然对这个问题感兴趣,请查看我对失败实验的编辑。谢谢。
标签: grails