ThreadLocal 与 Session 管理

  • Post author:
  • Post category:其他


如果没有将Hibernate的Session交由Spring管理,那管理session将会是一件比较麻烦的事情,刚开始学Hibernate的时候,看的视频教程多是基于javase的简单关系操作实现。后来在一个web项目中,持久层打算使用Hibernate,就傻傻的按照以前使用JDBC实现DAO的方式,不断的连接断开数据库,最要命的是还配置了

 <property name="hbm2ddl.auto">update</property>

最终结果就是效率极低,jvm内存满溢。

解决的问题的关键就是避免每次数据库操作都重新获取一个Session,要能实现Session重用,因为session并非线程安全,重用Session要保证线程安全。

可能很多人都知道这个方法,这里仅作为个人经验总结和交流之用–ThreadLocal(线程局部变量)。在JVM中为每个运行中的线程创建一个私有的存储空间,不会被其他线程访问.

以其中一个servlet为例:



private ThreadLocal session= new ThreadLocal();

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {


session.set(getSession());
dotask(request.getParameter("id"));

Session curSession = session.get();
if(curSession!=null)
{
curSession.flush();
curSession.close();
session.set(null);
}

}

private void dotask(String id)
{
Session tempSession =(Session)session.get();
Student stu=(Student)tempSession.get(Student.class,id);
StuClass stuCla = (StuClass)tempSession.get(StuClass.class,stu.getClassid());
}