2014-05-12 29 views
2

我想在同一個方法中有相同id的另一個域實體時,以分離狀態獲取grails中的域實體。在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會話分離?

回答

4

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

請問'userInstance.dirtyPropertyNames'工作'userInstance.save()' – TheKojuEffect

+0

沒有這也在使用前保存。一旦保存,所有髒屬性將被刷新爲新值。舊值將丟失。 – dmahapatro

+0

謝謝。 我正在使用Intellij,並且''不能解析'dirtyPropertyNames'和'userInstance.getPersistentValue'中的符號。任何想法? – TheKojuEffect