控制器邏輯:如何解決StaleObjectStateException使用JPA和Hibernate
def updateObject() {
Object o = Object.get(params.id as Long)
o.otherObjects.clear()
objectDataService.saveObject(o.id)
OtherObject newObject = new OtherObject;
o.addToOtherObjects(newObject)
objectDataService.saveObject(o.id)
}
ServiceLogic
def saveObject(long profileId) {
o.save(flush:true)
}
什麼的情況下,這只是工作的90%發生
。
問題
ERROR errors.GrailsExceptionResolver - StaleObjectStateException occurred when processing request: [GET] /controller/updateObject - parameters:
stuff[]: data
Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect) : [com.path.Object#1].
Stacktrace follows:
Message: Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect) : [com.path.Object#1]
我已經通過相關的問題閱讀,發現merge
叫你在上面看到。它解決了大約50%的案件,但不是全部。
如果你將這個邏輯轉移到一個服務方法中,那麼你會不會更好? – 2014-09-03 15:29:46
我不想超載該服務。你認爲這有意義嗎? – 2014-09-03 15:36:44
將業務邏輯轉移到服務並使您的控制器儘可能瘦(通過瘦我的意思是用更少的代碼行)總是更好。這將有助於您在任何需要的地方重複使用代碼,並在測試中節省大量時間。 – 2014-09-03 19:41:57