2011-03-01 88 views
1

我們通過基於java的腳本語言groovy使用hibernate。休眠更新持久記錄

我們檢索記錄,更新記錄並保存記錄。

更新期間,我們清除關聯,並在保存前重新載入這些關聯。

當關聯被刪除後,但在建立新關聯之前,Hibernate會刷新記錄,從而觸發驗證失敗,我們會得到一個異常。

即,我們對聯想的約束:

class Entity { 
    ... 
    static constraints = { 
     association1(minSize:1) //require association to have at least 1 record 
    } 
}

什麼是更新持久記錄的最佳方法?

一些潛在的選擇:

===================================== =========

[1]創造新的記錄並複製屬性:

 
def oldEntity = Entity.findByX(x) 
if (oldEntity) { 
    oldEntity.properties = newEntity.properties 
     oldEntity.save(flush:true);| 
} 
else { 
     newEntity.save(flush:true); 
}

這裏關注的是這種感覺哈克 - 建立在一個detatched實體和複製屬性在活的一個。

==============================================

[2]檢索記錄,更新,保存,齊平禁用:

 
sessionFactory.currentSession.flushMode = org.hibernate.FlushMode.MANUAL

def existingEntity = Entity.findByX(x) existingEntity.association1.clear() existingEntity.association2.clear()

existingEntity.association1.add(new Association(...)) existingEntity.association2.add(new Association(...))

sessionFactory.currentSession.flushMode = org.hibernate.FlushMode.AUTO existingEntity.save(flush:true)

不知道這做法 - 不喜歡與Hibernate的狀態管理

這種干擾=== ===========================================

[3]將刷新模式永久設置爲手動,並使用save()和save(flush:true)以級聯方式保留記錄:「all-delete-orphan」以確保管理關聯。

這裏的問題是這不是默認的 - 並依靠我們來管理Hibernate的沖洗。

==============================================

摘要:

所有這些方法似乎聞 - 任何人都可以建議針對這種情況最不壞的辦法 - 或者甚至是最佳做法?

感謝

亞歷

回答

1

我們的解決方案是將提交模式設置爲「commit」,只使用手動entity.save(flush:true)調用進行刷新,如果不回滾,則在事務結束時進行刷新。

Config.groovy中:

 
hibernate.flush.mode="commit" 

我們發現作爲一個怪癖,在DataSource.groovy中的設置並沒有工作,雖然這也許是更明顯的地方。另外新線程要求我們手動設置 - 更改不會自動提取。

EntityService.groovy:

 
import org.codehaus.groovy.grails.commons.ConfigurationHolder as CH

def sessionFactory

... sessionFactory.currentSession.flushMode = org.hibernate.FlushMode.parse(CH.config.hibernate.flush.mode.toUpperCase())

後者的代碼只似乎是在一個線程情況下,必要的,因爲新主題似乎並不儘管是另有情境感知要注意此設置。

0

對我來說,如果你真的要清除並重新創建這些關聯,第二種方法是具有少聞。

如果您需要操縱通過無效狀態的模型,將刷新模式設置爲手動沒有任何問題。

+0

感謝您的回覆,第四個選項發生 - 在更新期間從休眠狀態中分離(或逐出)記錄,然後在更新完成後重新關聯。 – Alex 2011-03-01 18:34:41