Hibernate——Session详解(一)

Hibernate在对资料库进行操作之前,必须先取得Session实例,相当于JDBC在对资料库操作之前,必须先取得Connection实例。

Session是Hibernate对数据库操作的基础,它不是我们所说的JSP页面传递参数的那个Session。Session是Hibernate运作的中心,对象的生命周期、事务的管理、数据库的存取都与session息息相关。

session是线程安全,且由sessionFactory得到。

取得session的前提条件是拿到SessionFactory,下面是Hibernate常用的两种拿到SessionFactory的方式

  1. 得到SessionFactory

方式一:

当在Myeclipse8以上的版本引入Myeclipse自带的Hibernate框架后,myeclipse会自动为项目创建一个HibernateSessionFactory类。

现在对代码进行解析

  1. package com.zhuxuli.HibernateSession;  
  2.   
  3. import javax.persistence.Entity;  
  4. import org.hibernate.HibernateException;  
  5. import org.hibernate.Session;  
  6. import org.hibernate.cfg.Configuration;  
  7.   
  8. /** 
  9.  * Configures and provides access to Hibernate sessions, tied to the 
  10.  * current thread of execution.  Follows the Thread Local Session 
  11.  * pattern, see {@link http://hibernate.org/42.html }. 
  12.  */  
  13. @Entity  
  14. public class HibernateSessionFactory {  
  15.   
  16.     /**  
  17.      * Location of hibernate.cfg.xml file. 
  18.      * Location should be on the classpath as Hibernate uses   
  19.      * #resourceAsStream style lookup for its configuration file.  
  20.      * The default classpath location of the hibernate config file is  
  21.      * in the default package. Use #setConfigFile() to update  
  22.      * the location of the configuration file for the current session.    
  23.      */  
  24.       
  25.     private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";  
  26.     private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();  
  27.     private  static Configuration configuration = new Configuration();      
  28.     private static org.hibernate.SessionFactory sessionFactory;  
  29.     private static String configFile = CONFIG_FILE_LOCATION;  
  30.       
  31.     static {  
  32.         try {  
  33.             configuration.configure(configFile);  
  34.             sessionFactory = configuration.buildSessionFactory();  
  35.         } catch (Exception e) {  
  36.             System.err  
  37.                     .println("%%%% Error Creating SessionFactory %%%%");  
  38.             e.printStackTrace();  
  39.         }  
  40.     }  
  41.     private HibernateSessionFactory() {  
  42.     }  
  43.       
  44.     /** 
  45.      * Returns the ThreadLocal Session instance.  Lazy initialize 
  46.      * the <code>SessionFactory</code> if needed. 
  47.      * 
  48.      *  @return Session 
  49.      *  @throws HibernateException 
  50.      */  
  51.     public static Session getSession() throws HibernateException {  
  52.         Session session = (Session) threadLocal.get();  
  53.   
  54.         if (session == null || !session.isOpen()) {  
  55.             if (sessionFactory == null) {  
  56.                 rebuildSessionFactory();  
  57.             }  
  58.             session = (sessionFactory != null) ? sessionFactory.openSession()  
  59.                     : null;  
  60.             threadLocal.set(session);  
  61.         }  
  62.   
  63.         return session;  
  64.     }  
  65.   
  66.     /** 
  67.      *  Rebuild hibernate session factory 
  68.      * 
  69.      */  
  70.     public static void rebuildSessionFactory() {  
  71.         try {  
  72.             configuration.configure(configFile);  
  73.             sessionFactory = configuration.buildSessionFactory();  
  74.         } catch (Exception e) {  
  75.             System.err  
  76.                     .println("%%%% Error Creating SessionFactory %%%%");  
  77.             e.printStackTrace();  
  78.         }  
  79.     }  
  80.   
  81.     /** 
  82.      *  Close the single hibernate session instance. 
  83.      * 
  84.      *  @throws HibernateException 
  85.      */  
  86.     public static void closeSession() throws HibernateException {  
  87.         Session session = (Session) threadLocal.get();  
  88.         threadLocal.set(null);  
  89.   
  90.         if (session != null) {  
  91.             session.close();  
  92.         }  
  93.     }  
  94.   
  95.     /** 
  96.      *  return session factory 
  97.      * 
  98.      */  
  99.     public static org.hibernate.SessionFactory getSessionFactory() {  
  100.         return sessionFactory;  
  101.     }  
  102.   
  103.     /** 
  104.      *  return session factory 
  105.      * 
  106.      *  session factory will be rebuilded in the next call 
  107.      */  
  108.     public static void setConfigFile(String configFile) {  
  109.         HibernateSessionFactory.configFile = configFile;  
  110.         sessionFactory = null;  
  111.     }  
  112.   
  113.     /** 
  114.      *  return hibernate configuration 
  115.      * 
  116.      */  
  117.     public static Configuration getConfiguration() {  
  118.         return configuration;  
  119.     }  
  120.   
  121. }  

然后写一个测试类 test

  1. public static void main(String args[]) {  
  2.         Session session = null;  
  3.         Transaction tx = null;  
  4.   
  5.         try {  
  6.             session = HibernateSessionFactory.getSession();  
  7.             tx = session.beginTransaction();  
  8.             User user = new User();  
  9.             user.setUsername("乔丹");  
  10.             user.setUserpass("123");  
  11.             session.save(user);  
  12.             System.out.println("数据成功写入....");  
  13.         } catch (Exception e) {  
  14.             e.printStackTrace();  
  15.             tx.rollback();  
  16.         } finally {  
  17.             session.close();  
  18.         }  
  19.   
  20.     }  

可以看到,session直接由HibernateSessionFactory得到。

方式二:

直接在类中读取Hibernate.cfg.xml文件,得到SessionFactory

  1. public static void main(String args[]) {  
  2.         Configuration config = new Configuration()  
  3.                 .configure("/hibernate.cfg.xml");  
  4.         SessionFactory sessionFactory = config.buildSessionFactory();  
  5.         Session session = sessionFactory.openSession();  
  6.         Transaction tx = session.beginTransaction();  
  7.         User user = new User();  
  8.         user.setUsername("乔丹");  
  9.         user.setUserpass("123");  
  10.         session.save(user);  
  11.         tx.commit();  
  12.     }  


以上例子可以看到,得到了SessionFactory后,就可以得到Session,然后对数据进行操作。

2.得到Session的两种方式

得到Session有两种方式一个是方法getCurrentSession(),另一个是方法OpenSession()。

两种方法的区别是:
getCurrentSession():无论在什么地方调用,都返回同一个Session

OpenSession()重新建立一个新的Session

在一个应用程序中,如果DAO 层使用Spring 的hibernate 模板,通过Spring 来控制session 的生命周期,则首选getCurrentSession ()。
1. 如果使用的是getCurrentSession来创建session的话,在commit后,session就自动被关闭了,
也就是不用再session.close()了。但是如果使用的是openSession方法创建的session的话,
那么必须显示的关闭session,也就是调用session.close()方法。这样commit后,session并没有关闭
2.  使用SessionFactory.getCurrentSession()需要在hibernate.cfg.xml中如下配置:
* 如果是在本地,可以通过以下配置:
<property name="hibernate.current_session_context_class">thread</property>
* 如果采用了JTA事务配置如下 
<property name="hibernate.current_session_context_class">jta</property>
getcurrentSession()方法总是会返回“当前的”工作单元。
Session 在第一次被使用的时候,即第一次调用getCurrentSession()的时候,其生命周期就开始。然后她被Hibernate绑定到当前线程。当事物结束的时候,不管是提交还是回滚,Hibernate会自动把Session从当前线程剥离,并且关闭。若在次调用 getCurrentSession(),会得到一个新的Session,并且开始一个新的工作单元。这是Hibernate最广泛的thread- bound model,支持代码灵活分层(事物划分和数据访问代码的分离)。

Session在hibenate3.0以上版本,默认是JTX,通过getCurrentSession()将Session和Transaction进行绑定,Transaction无论是commit, 还是rollback都会关闭session。
通过配置,session和Thread进行绑定,Transaction无论是commit, 还是rollback都会关闭session。

版权声明:本文为博主原创文章,未经博主允许不得转载。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值