grails - 登录事件监听器中的另一个事务错误更新或删除了行?

标签 grails spring-security

我有一个简单的Spring Security登录事件侦听器注册为

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)

我想知道如何避免此错误?感谢您的帮助!谢谢!

最佳答案

尝试使用锁

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

关于grails - 登录事件监听器中的另一个事务错误更新或删除了行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44536159/

相关文章:

git - IntelliJ Grails支持+ Git

grails - grails helloworld应用程序给出异常

java - 使用 Spring Security 处理静态资源

java - 不同的url采用不同的认证方式

java - 简单的 Spring Security 要求

spring - 在 Spring Security 中实现 Basic Auth 后总是收到 401 错误

hibernate - 从Hibernate Grails中选择数据库

ajax - Grails将部分模板渲染为Div

java - Grails/java 单资源池线程队列

java - 仅检查 SAML 身份验证,不转发