public final class HibernateUtil{ private static SessionFactory sessionFactory;
private static ThreadLocal session=new ThreadLocal(); private HibernateUtil(){ } static{ Configuration cfg=new Configuration(); cfg.configure();//默认的是classpath sessionFactory=cfg.buildSessionFactory(); }
pulic static Session getThreadLocalSession(){ Session s=(Session)session.get(); if(s==null){ s=getSession(); session.set(s); } return s; }
public static void closeSession(){ Session s=(Session)session.get(); if(s!=null){ s.close(); session.set(null); }
}
public static SessionFactory getSessionFactory(){ return sessionFactory; } public static Session getSession(){ return sessionFactory.openSession(); }
|
OpenSessionInView:作用:解决懒加载(session是否关闭)和事务问题(持久层中是否出现事务代码)
public class OpenSessionInView inplements javax.sevlet.Filter{ ......... public void doFilter(ServletRequest arg0,ServletResponse arg1,FilterChain arg2)throws IOException,ServletException{ Session session=null; Transaction tx=null; try{ session=HibernateUtil.getThreadLocalSession(); tx=session.beginTransaction(); arg2.doFilter(arg0,arg1); tx.commit(); }catch(Exception e){ if(tx!=null) tx.rollback(); throw new RuntimeException(e.getMessage(),e) }finally{ HibernateUtil.closeSession(); } }
.......
}
|
持久化类:
public class UserDAO{ public void addUser(user){ HibernateUtil.getThreadLocalSession().save(user); }
|
阅读(947) | 评论(0) | 转发(0) |