【问题标题】:Get detached domain entity in grails在 grails 中获取分离的域实体
【发布时间】:2014-05-12 04:11:15
【问题描述】:

当在同一方法中存在具有相同 id 的另一个域实体时,我希望在 grails 中获得一个处于分离状态的域实体。

我遵循How do you disconnect an object from it's hibernate session in grails? 作为在 grails 中获取分离域实体的一种方式。

def id = 23L;
def userInstance = User.get(id)
def oldInstance = User.get(id).discard()

userInstance.properties = params

userInstace.save(flush:true)

// Now, I want to compare properties of oldInstance and userInstance
// But I get null for oldInstance

那么,如何在 grails 中详细获取域实体,使其与 gorm 会话分离?

【问题讨论】:

    标签: hibernate grails grails-orm detach


    【解决方案1】:

    discard 不返回实例本身。它不返回任何内容(void),但会驱逐将来持久化的对象。将其用作:

    def oldInstance = User.get(id)
    oldInstance.discard()
    

    附带说明,如果唯一的原因是比较实例中属性的新旧值,那么您可以使用dirtyPropertyNamesgetPersistentValue() 在刷新实例之前如下:

    userInstance.properties = params
    
    userInstance.dirtyPropertyNames?.each { name ->
        def originalValue = userInstance.getPersistentValue( name )
        def newValue = userInstance.name
    }
    
    //Or groovier way
    userInstance.dirtyPropertyNames?.collect { 
        [
            (it) : [oldValue: userInstance.getPersistentValue( it ), 
                    newValue: userInstance.it] 
        ] 
    }
    

    【讨论】:

    • 调用userInstance.save()userInstance.dirtyPropertyNames会工作
    • 没有这个必须在保存前使用。保存后,所有脏属性都将被刷新为新值。旧值将丢失。
    • 谢谢。我正在使用 Intellij,我在 dirtyPropertyNamesuserInstance.getPersistentValue 中得到了 cannot resolve symbol。有什么想法吗?
    • 当我从数据库中加载一个域,然后更改一些属性,然后在一个字段上调用getPersistentValue,它到底返回了什么?我猜这是最初从数据库加载的值,它实际上并没有进行另一个数据库查询来获取字段的当前值,对吧?我的观点是,有可能在从数据库初始加载域到我想将其保存回来之间,其他一些线程已经覆盖了数据库中的记录,我需要从数据库中获取当前值,而无需丢失对域所做的更改。
    • 所以我试图从域内的数据库中加载域的另一个实例,比如def current = get(id),但它实际上返回了相同的域实例,所以current == this。当我调用current.refresh() 时,它实际上会从数据库重新加载数据,但它也会更新this,因此我会丢失对其所做的所有更改。我需要保持this 不变,同时从数据库中加载当前数据,以便比较thiscurrent 之间的差异。请问可以吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-10
    • 2018-10-25
    • 2012-11-12
    • 1970-01-01
    相关资源
    最近更新 更多