2013-09-03 23 views
9

私は次のようにします。StaleObjectStateException:行が別のトランザクションによって更新または削除されましたか?

def currentUser = springSecurityService.currentUser 
currentUser.name = "test" 
currentUser.save(flush: true) 

// some other code 

currentUser.gender = "male" 
currentUser.save(flush: true)  // Exception occurs 

これは私が得る例外です:

ERROR events.PatchedDefaultFlushEventListener - Could not synchronize database state with session 
org.hibernate.StaleObjectStateException: Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect) 

どのように私はこのエラーを防ぐことができますか?そのための最良の解決策は何ですか?あなたは1は、私が使用する必要がありますmerge()

を使用することができますdiscard()

  • hereを使用することができます

    1. here

      は、私は別のアプローチを見つけましたか?

  • 答えて

    10

    mergeを使用すると、オブジェクトがデータベースの現在の状態と一致するように更新されます。破棄を使用すると、オブジェクトがデータベースの内容にリセットされ、変更が破棄されます。あなたが自分で管理する必要がある休止セッションの他のすべて。

    さらに重要なコードは、データベースのトランザクションが存在するように、サービスで記述する必要があります、あなたは一度だけで終わりに

    save(flush:true) 
    

    を使用する必要があります。

    def currentUser = springSecurityService.currentUser 
    currentUser.name = "test" 
    
    // currentUser.save(flush: true) // removing this line because if a rollback occurs, then changes before this would be persisted. 
    
    
    // some other code 
    
    currentUser.gender = "male" 
    currentUser.merge()     // This will merge persistent object with current state 
    currentUser.save(flush: true) 
    
    +0

    私のコードは、あなたがそれがそうするはずのやり方で書き直せますか? –

    +0

    ご確認の上、ご不明な点がありましたらお知らせください。ありがとう!!! –

    関連する問題