Get detached domain entity in grails

别来无恙 提交于 2019-12-24 05:38:06

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/23600922/get-detached-domain-entity-in-grails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!