Gorm级联操作



我正在尝试理解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

Hibernate不支持级联的"ON DELETE SET NULL"。因此,如果你拥有的对象由多个所有者拥有,如果你删除其中一个所有者,那么拥有的对象就不会被删除。

您很可能会得到"InvalidDataAccessApiUsageException:已删除的对象将通过级联重新保存"或FK约束违反异常

请参阅这个类似的问题

最新更新