【问题标题】:Gorm cascaded operationsGorm级联操作
【发布时间】: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


【解决方案1】:

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

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

看到这个similar question

【讨论】:

    猜你喜欢
    • 2012-09-07
    • 2020-03-10
    • 2014-05-08
    • 1970-01-01
    • 2013-06-01
    • 2014-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多