문제

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] 
    ] 
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top