我是用Struts2、hibernate做的一个程序。
发现
当一个用户登录以后程序会给他分配多个线程,而不是一个,执行相同的操作也是线程都不一样的。
但是这样就存在一个问题了啊。hibernate中的
HibernateSessionFactory类的getSession()方法用的是ThreadLocal来为每一个线程创建一个session,这样的话其实一个用户就给他创建了多个session了啊。打印出来的代码如下:thread id=17
thread=Thread[http-8080-2,5,main]
session=null
thread id=19
thread=Thread[http-8080-4,5,main]
session=nullthread id=19
thread=Thread[http-8080-4,5,main]
session=org.hibernate.impl.SessionImpl(<closed>)thread id=17
thread=Thread[http-8080-2,5,main]
session=org.hibernate.impl.SessionImpl(<closed>)thread id=17
thread=Thread[http-8080-2,5,main]
session=org.hibernate.impl.SessionImpl(<closed>)thread id=18
thread=Thread[http-8080-3,5,main]
session=null
select count(*) from Torder as model where model.ostatus=:ostatusthread id=18
thread=Thread[http-8080-3,5,main]
session=org.hibernate.impl.SessionImpl(<closed>)thread id=19
thread=Thread[http-8080-4,5,main]
session=org.hibernate.impl.SessionImpl(<closed>)thread id=19
thread=Thread[http-8080-4,5,main]
session=org.hibernate.impl.SessionImpl(<closed>)thread id=18
thread=Thread[http-8080-3,5,main]
session=org.hibernate.impl.SessionImpl(<closed>)thread id=18
thread=Thread[http-8080-3,5,main]
session=org.hibernate.impl.SessionImpl(<closed>)thread id=19
thread=Thread[http-8080-4,5,main]
session=org.hibernate.impl.SessionImpl(<closed>)thread id=19
thread=Thread[http-8080-4,5,main]
session=org.hibernate.impl.SessionImpl(<closed>)thread id=18
thread=Thread[http-8080-3,5,main]
session=org.hibernate.impl.SessionImpl(<closed>)thread id=18
thread=Thread[http-8080-3,5,main]
session=org.hibernate.impl.SessionImpl(<closed>)thread id=17
thread=Thread[http-8080-2,5,main]
session=org.hibernate.impl.SessionImpl(<closed>)thread id=17
thread=Thread[http-8080-2,5,main]
session=org.hibernate.impl.SessionImpl(<closed>)
可以看到里面总共使用了4个线程,4个session(hibernate的session)这样应该和HibernateSessionFactory类的getSession方法的初衷不一样的吧

解决方案 »

  1.   

    这恰好符合hibernate的机制是正确的啊,
    试想,如果你4个线程用一个Session,会有什么样的后果?
    轮奸也要讲究顺序啊,难道你想搞4p,第一个人开了session,还没搞完,第2个人就把它关了,哟
    那就符合hibernate的初衷了!!!
      

  2.   


    那位什么tomcat要为一个用户分配4个线程啊,它线程的分配机制是怎么样的啊。
      

  3.   

    真是佩服你,思绪跳跃都不需要任何理由的。。
    这又和tomcat扯上什么关系了,我记得你在讨论struts,hibernate
    而且你刚才说的4个线程怎么又变成tomcat分配了呢,麻烦你讨论话题的时候有个中心点
    要过渡也要打声招呼啊?
      

  4.   

    不好意思啊,我是初学啊。
    为每一个用户分配线程不是tomcat完成的嘛,我在程序中也不存在新建线程的啊。
      

  5.   

    不知所云!
    请搞清楚两个Session 的 意义。
    请搞清楚Hibernate中Session的生命周期。
    请搞清楚请求响应机制。