【问题标题】:Differences between MongoDB and Hibernate GORM for cascadingMongoDB 和 Hibernate GORM 级联的区别
【发布时间】:2013-06-01 10:30:53
【问题描述】:

我正在构建一个 Grails 应用程序,当从 MongoDB GORM 插件切换到 Hibernate 插件时,我在集成测试中得到了一些奇怪的结果。

我有一个一对多关系中的 Client 和 Workspace 类:

class Client{
    //fields...
    static hasMany = [workspaces: Workspace]
}

class Workspace{
    //fields...
    static belongsTo = [client: Client]
}

然后在运行以下 Spock 集成测试时:

def "Deleting a client removes its related workspaces" () {

    given: "An existing client and workspace"
    Client client =  new Client().save(failOnError: true)
    Workspace workspace = new Workspace().save(failOnError: true)
    client.addToWorkspaces(workspace)

    when: "Deleting the client"
    def foundClient = Client.get(client.id)
    foundClient.delete(flush: true)
    assert !Client.exists(client.id)

    then: "Related workspace is also deleted"
    !Workspace.exists(workspace.id)
}

此测试将在 Hibernate 下通过,但在 MongoDB 运行时不会通过。 MongoDB 不会删除工作区,因此测试的最后一行将失败:

Workspace.count() == 0
          |       |
          1       false

有没有办法让 MongoDB 使用 GORM 执行与 Hibernate 相同的级联操作?

感谢您的帮助

【问题讨论】:

  • 你得到了什么解决方案?

标签: hibernate mongodb grails grails-orm


【解决方案1】:

相信你可以使用 GORM 中的beforeDelete 拦截器来获得你想要的效果。比如:

def beforeDelete() {
    Workspace.withNewSession { 
        def ws = Workspace.findByClient(id)
        if (ws) {
            ws.delete(flush:true)
        }
    }
}

【讨论】:

    猜你喜欢
    • 2012-07-31
    • 2014-06-03
    • 2012-09-07
    • 1970-01-01
    • 1970-01-01
    • 2013-02-06
    • 1970-01-01
    • 1970-01-01
    • 2011-11-17
    相关资源
    最近更新 更多