Gorm级联操作

时间:2015-03-20 22:22:37

标签: grails

我试图了解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放入了我自己的班级,将hasMany置于我的班级班级。

输出:

...........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

1 个答案:

答案 0 :(得分:1)

Hibernate不支持“ON DELETE SET NULL”进行级联。因此,如果您拥有的对象由多个所有者拥有,则如果您删除其中一个所有者,则不会删除拥有的对象。

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

请参阅此similar question