2017-06-14 30 views
0

我有一個簡單的彈簧安全登錄事件偵聽器註冊爲通過登錄事件偵聽器中的另一個事務錯誤更新或刪除了行?

class LoginEventListener implements 
    ApplicationListener<InteractiveAuthenticationSuccessEvent> { 

    //deal with successful login 
    void onApplicationEvent(InteractiveAuthenticationSuccessEvent event) { 
     User.withTransaction { 

      def user = User.get(event.authentication.principal.id) 
      user.lastLoginTime = new Date() // update login time 
      user.save() 

     } 


    } 


} 

在日誌中每隔幾登錄嘗試我得到的錯誤是

ERROR 2017-06-13 16:24:04,090 [ajp-bio-8109-exec-4561] 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): [User#2876] 
    at org.grails.datastore.gorm.GormStaticApi.withTransaction(GormStaticApi.groovy:686) 
    at com.runnercard.LoginEventListener.onApplicationEvent(LoginEventListener.groovy:12) 
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) 
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) 
    at java.lang.Thread.run(Thread.java:745) 

我想知道我怎樣才能避免這種情況錯誤?我感謝任何幫助!謝謝!

回答

1

嘗試使用鎖

def user = User.get(event.authentication.principal.id ,[lock: true]) 
+0

生病看是否能解決問題。謝謝! – kofhearts

+0

謝謝你解決了這個問題! – kofhearts