2014-09-02 57 views
1

您可以強制Grails中的DomainClass.get(id)功能從數據庫中提取新實例,而不是使用先前在會話中檢索到的本地副本?Grails - 從數據庫中檢索新鮮實例

我想比較,如果該實例的屬性發生了變化:

def myInstance = MyClass.get(params.id) 
    myInstance.properties = params.data // updates the instance, but does not save it 

    // stuff happens 

    def myDbInstance = MyClass.get(params.id) // would like this to pull a fresh copy from the database, unchanged to allow for comparison 
    if(myDbInstance.value != myInstance.value) { 
     // do something if has changed 
    } 

謝謝。

+3

查看['getPersistentValue()'](http://grails.org/doc/latest/ref/Domain%20Classes/getPersistentValue.html)和['isDirty()'](http:// grails .ORG/DOC /最新/ REF /域%20Classes/isDirty.html)。 – dmahapatro 2014-09-02 15:37:23

回答

0

使用可以使用refresh()方法強制實例從數據庫重新加載。

0

如果我們想比較視圖中更新的字段與數據庫中已有的字段,那麼refresh()會更新尚未保存在數據庫中的實例。 在這種情況下,實例上的getPersistentValue('field_name')將獲取數據庫中的值並可用於比較。

如果employeeAllocationInstance已經可以在控制器的說明如 更新行動,我們要比較的更新的字段可以說jan分配 然後

existing_allocation = EmployeeAllocation.get(employeeAllocationInstance.id)

將有值employeeAllocationInstance更新,所以我們可以做

existing_allocation?.getPersistentValue('jan')?.value得到存儲在數據庫中的值(還有待更新)