Hibernate的session是怎么创建的

   Hibernat 对数据库的操作是通过Session来实现的,这里的session不同于页面间传递参数的session,
而是类似于JDBC中的 Connection。Session是Hibernate运作的中心,对象的生命周期、事务的管理、数据库的存取都与session息息相关。
  Session是由HibernateSessionFactory创建的,是线程安全的,可以让多个执行线程同时存取     
   HibernateSessionFactory而不会有数据共享的问题,但不能让多个线程共享一个Session。
   SessionFactory对象的创建:
  
      Configuration cfg = new Configuration().configure();
      SessionFactory sessions = cfg.buildSessionFactory();
   

   session创建时使用了一个ThreadLocal类来建立一个Session管理的辅助类,使用ThreadLocal可以有效隔离执行所用的数据,
避开了Session的多线程之间的数据共享问题。

   //创建一个线程本地变量。
public static final ThreadLocal<Session> threadlocal = new ThreadLocal<Session>();
		public static org.hibernate.SessionFactory sessionFactory;
		 
		//获取session的方法
		public static Sessin getSession() throws HibernateException{
				//返回线程局部变量的当前线程的值
				Session s = (Session)threadLocal.get();
				//如果sessionFactory为空,重新创建sessionFactory;如果线程为空,就打开一个新的session
				if(session==null || !session.isOpen()){
				if(sessionFactory == null){
				rebuildSessionFactory(); session = (sessionFactory != null) sessionFactory.openSession():null;
				// 将hibernate的session放入到线程中保存;只要这个线程不结束,都可以通过线程的get()方法来获取
				threadLocal.set(session);return session;
		}

猜你喜欢

转载自wuxw920.iteye.com/blog/1697153