我想在同一个方法中存在另一个相同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会话分离?
答案 0 :(得分:4)
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
}
//Or groovier way
userInstance.dirtyPropertyNames?.collect {
[
(it) : [oldValue: userInstance.getPersistentValue( it ),
newValue: userInstance.it]
]
}