2

我有 HttpSessionListener 来监听会话的创建和销毁时间。我有一个用户域,它已登录布尔列,每当用户登录或注销时我都会更新它,用于管理管理。我还将会话 ID 存储在数据库中。

我还想在会话被销毁时更新loggedIn列。下面是用 sessionDestroyed 方法编写的代码。

def user = User.findByUserSessionId(session.getId())
if(user) {      
    user.setLoggedIn(false)
    user.setUserSessionId("SESSION DESTROYED")
    user.save(flush: true)      
 }

问题是用户表永远不会更新。

以下是日志文件中报告的错误:

            [2010-10-16 11:45:07.781] ERROR core.ContainerBase.[Tomcat].[localhost].[/SAMPLE] Session event listener threw exception
        org.hibernate.HibernateException: No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here
            at org.springframework.orm.hibernate3.SpringSessionContext.currentSession(SpringSessionContext.java:63)
            at org.hibernate.impl.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:574)
            at org.codehaus.groovy.grails.orm.hibernate.validation.HibernateDomainClassValidator.validate(HibernateDomainClassValidator.java:66)
            at org.codehaus.groovy.grails.orm.hibernate.metaclass.AbstractSavePersistentMethod.doInvokeInternal(AbstractSavePersistentMethod.java:129)
            at org.codehaus.groovy.grails.orm.hibernate.metaclass.AbstractDynamicPersistentMethod.invoke(AbstractDynamicPersistentMethod.java:59)
            at sun.reflect.GeneratedMethodAccessor500.invoke(Unknown Source)
            at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
            at java.lang.reflect.Method.invoke(Method.java:597)
            at org.codehaus.groovy.runtime.callsite.PojoMetaMethodSite$PojoCachedMethodSite.invoke(PojoMetaMethodSite.java:188)
            at org.codehaus.groovy.runtime.callsite.PojoMetaMethodSite.call(PojoMetaMethodSite.java:52)
            at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:132)
            at org.codehaus.groovy.grails.plugins.orm.hibernate.HibernatePluginSupport$_addBasicPersistenceMethods_closure71.doCall(HibernatePluginSupport.groovy:812)

我能知道在会话被破坏时如何正确更新用户表吗?

谢谢你。杰伊·钱德兰。

4

1 回答 1

2

尝试

User.withTransaction{ txStatus ->    .... }

或者

User.withSession{ session - > .... }

或者也许注入一个服务来做你需要它做的事情,因为服务方法默认应该有事务。

编辑——通常我不会走这么远,但我今天心情很好......像下面这样的东西应该可以工作。您真的应该阅读 grails 文档或购买一本书...

User.withTransaction( txStatus -> 
    def user = User.findByUserSessionId(session.getId())
    if(user) {      
       user.setLoggedIn(false)
       user.setUserSessionId("SESSION DESTROYED")
       user.save(flush: true)      
    }
}
于 2010-10-16T18:56:46.937 回答