在grails中获取分离的域实体 [英] Get detached domain entity in grails

查看:182
本文介绍了在grails中获取分离的域实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我跟着这个如何从grails中的hibernate会话中断开一个对象?作为在grails中获得分离域实体的一种方式。

  def id = 23L; 
def userInstance = User.get(id)
def oldInstance = User.get(id).discard()
$ b userInstance.properties = params

userInstace.save(flush:true)

//现在,我想比较oldInstance和userInstance
的属性//但是,对于oldInstance



那么,我如何才能在grails中获取一个域实体,以便从gorm会话中分离出来?

解决方案

discard 不返回实例本身。它不会返回任何东西(void),但会将未来持续存在的对象逐出。使用它:

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

请注意,如果唯一的原因是比较实例中属性的旧值和新值,那么您可以使用 dirtyPropertyNames getPersistentValue() 刷新实例,如下所示:

  userInstance.properties = params 

userInstance.dirtyPropertyNames?.each {name - >
def originalValue = userInstance.getPersistentValue(name)
def newValue = userInstance.name
}

//或者更换方式
userInstance.dirtyPropertyNames ?.收集{
[
(it):[oldValue:userInstance.getPersistentValue(it),
newValue:userInstance.it]
]
}


I want to get a domain entity in grails in detached state when there is another domain entity for same id in same method.

I followed this How do you disconnect an object from it's hibernate session in grails? as a way to get a detached domain entity in 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

So, how can I get a domain entity in grails in details such that it is detached from gorm session?

解决方案

discard does not return the instance itself. It returns nothing (void) but evicts the object getting persisted in future. Use it as:

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

On a side note, if the sole reason is to compare the old and new values of the properties in the instance then you can use dirtyPropertyNames and getPersistentValue() before flushing the instance as below:

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] 
    ] 
}

这篇关于在grails中获取分离的域实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆