Hibernate session管理
来源:互联网 发布:centos cpu 编辑:程序博客网 时间:2024/05/17 04:23
SessionFactory负责创建Session,SessionFactory是线程安全的,多个并发线程可以同时访问一个SessionFactory 并从中获取Session 实例。而Session并非线程安全,也就是说,如果多个线程同时使用一个Session实例进行数据存取,则将会导致Session 数据存取逻辑混乱。
1 它使用了ThreadLocal类别来建立一个 Session管理的辅助类
这是Hibernate Session管理一个广为应用的解决方案,ThreadLocal是Thread- Specific Storage模式的一个运作实例
HibernateUtil.java import net.sf.hibernate.*; import net.sf.hibernate.cfg.*; public class HibernateUtil { private static Log log = LogFactory.getLog(HibernateUtil.class); private static final SessionFactory sessionFactory; static { try { // Create the SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory(); } catch (Throwable ex) { log.error("Initial SessionFactory creation failed.", ex); throw new ExceptionInInitializerError(ex); } } public static final ThreadLocal session = new ThreadLocal(); public static Session currentSession() throws HibernateException { Session s = (Session) session.get(); // Open a new Session, if this Thread has none yet if (s == null) { s = sessionFactory.openSession(); session.set(s); } return s; } public static void closeSession() throws HibernateException { Session s = (Session) session.get(); session.set(null); if (s != null) s.close(); } }2 在Web应用程序中,我们可以藉助Filter来进行Session管理,在需要的时候开启Session,并在Request结束之后关闭Session
public class PersistenceFilter implements Filter { protected static ThreadLocal hibernateHolder = new ThreadLocal(); public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { hibernateHolder.set(getSession()); try { chain.doFilter(request, response); } finally { Session session = (Session) hibernateHolder.get(); if (session != null) { hibernateHolder.set(null); try { session.close(); } catch (HibernateException ex) { throw new ServletException(ex); } } } } }
- Hibernate中的Session管理
- Hibernate中的Session管理
- Hibernate 管理session
- hibernate session管理
- Hibernate session管理
- Hibernate 的 session 管理
- Hibernate(十三)Session管理
- Hibernate管理Session
- spring 管理hibernate session
- Hibernate 管理 Session
- Hibernate的session管理
- Hibernate中的Session管理
- Hibernate入门25 - Session 管理
- 利于ThreadLocal管理Hibernate Session
- ServletFilter中管理Hibernate Session
- 利于ThreadLocal管理Hibernate Session
- Hibernate中对Session管理
- Hibernate中Session的管理
- Spring3+Struts2+JPA2.0
- rehat yum 问题:This system is not registered with RHN
- JNI中反向访问Java对象
- ant——编译打包
- nefu 三国之战
- Hibernate session管理
- 用户输入字符串,输出所有排列 java
- 深入理解JVM
- ActiveX控件测试容器
- 全排列的题目
- javascript3个转义函数
- ERP解决方案选型指导
- LWJGL显示一 显示
- Android学习13--使用Intent和IntentFilter进行通信