Hibernate中两种获取Session的方式 (转)

来源:互联网 发布:人工智能主要应用领域 编辑:程序博客网 时间:2024/04/25 08:29

转自: http://blog.csdn.net/yingjiebohe/article/details/8283185

 

Session:是应用程序与数据库之间的一个会话,Hibernate运作的中心,持久层操作的基础.对象的生命周期/事务的管理/数据库的存取都与Session息息相关.

  Session对象是通过SessionFactory构建的,下面举个例子来介绍Hibernate两种获取session的方式。

  日志,是编程中很常见的一个关注点.用户在对数据库进行操作的过程需要将这一系列操作记录,以便跟踪数据库的动态.那么一个用户在向数据库插入一条记录的时候,就要向日志文件中记录一条记录,用户的一系列操作都要在一个Session中进行,否则这就成为了两个线程.不能保证同步.看下面的代码

     HibernateUtil管理Session的工具类

 

[java] view plaincopyprint?
  1. package com.bjpowernode.usermgr.util; 
  2.  
  3. import org.hibernate.Session;//hibernate3的 
  4. import org.hibernate.SessionFactory; 
  5. import org.hibernate.cfg.Configuration; 
  6.  
  7. public class HibernateUtils { 
  8.    private static SessionFactory factory; 
  9.      
  10.    static
  11.            try
  12.             //读取hibernate.cfg.xml文件 
  13.             Configuration cfg=new Configuration().configure(); 
  14.               
  15.             //建立SessionFactory 
  16.             factory=cfg.buildSessionFactory(); 
  17.     
  18.            }catch(Exception e){ 
  19.               e.printStackTrace();  
  20.            } 
  21.    }   
  22.     
  23.       //获得开启着的Session 
  24.    public static Session getSession(){ 
  25.        return factory.openSession(); 
  26.    } 
  27.     
  28.       //关闭Session 
  29.    public staticvoid closeSession(Session session){ 
  30.        if(session!=null){ 
  31.            if(session.isOpen()){ 
  32.                session.close(); 
  33.            } 
  34.        } 
  35.    } 
  36.     
  37.    public static SessionFactory getSessionFactory(){ 
  38.        return factory; 
  39.    } 
[java] view plaincopyprint?
  1. 用户业务逻辑层 
  2. package com.bjpowernode.usermgr.manager; 
  3.  
  4. import java.util.Date; 
  5.  
  6. import org.hibernate.Session; 
  7.  
  8. import com.bjpowernode.usermgr.domain.Log; 
  9. import com.bjpowernode.usermgr.domain.User; 
  10. import com.bjpowernode.usermgr.util.HibernateUtils; 
  11.  
  12. public class UserManagerImplimplements UserManager { 
  13.  
  14.       /**
  15.     * 添加用户和添加日志都使用了同一个Session,所以
  16.     * 当用户添加失败的时候,日志也会添加失败。事务回滚
  17.     * 用户添加成功日志也会添加成功
  18.     */ 
  19.     public void addUser(User user) { 
  20.          
  21.         Session session=null
  22.         try
  23.             //取得当前线程Session 
  24.             session=HibernateUtils.getSessionFactory().getCurrentSession(); 
  25.             session.beginTransaction(); 
  26.              
  27.             //保存用户 
  28.             session.save(user); 
  29.              
  30.             Log log=new Log(); 
  31.             log.setType("操作日志"); 
  32.             log.setTime(new Date()); 
  33.             log.setDetail("XXX"); 
  34.              
  35.             LogManager logManager=new LogManagerImpl(); 
  36.             //保存日志 
  37.             logManager.addLog(log); 
  38.              
  39.             session.getTransaction().commit(); 
  40.              
  41.         }catch(Exception e){ 
  42.             e.printStackTrace(); 
  43.             session.getTransaction().rollback(); 
  44.         } 
  45.     } 
  46.  
  47.  
  48. 日志实现类: 
  49. package com.bjpowernode.usermgr.manager; 
  50.  
  51. import org.hibernate.Session; 
  52.  
  53. import com.bjpowernode.usermgr.domain.Log; 
  54. import com.bjpowernode.usermgr.util.HibernateUtils; 
  55.  
  56. public class LogManagerImplimplements LogManager { 
  57.  
  58.  
  59.     public void addLog(Log log) { 
  60.          
  61.         //获取当前线程的Session 
  62.         HibernateUtils.getSessionFactory().getCurrentSession().save(log); 
  63.  
  64.     } 
  65.  
  66.  
  67. 测试类 
  68. package com.bjpowernode.usermgr.manager; 
  69.  
  70. import junit.framework.TestCase; 
  71.  
  72. import com.bjpowernode.usermgr.domain.User; 
  73.  
  74. public class UserManagerImplTestextends TestCase { 
  75.  
  76.     public void testAddUser() { 
  77.         UserManager userManager=new UserManagerImpl(); 
  78.         User user=new User(); 
[java] view plaincopyprint?
  1.     user.setName("张三"); 
  2.     userManager.addUser(user); 

注意:

1.openSession和getCurrentSession的区别?

   *openSession必须关闭,currentSession在事务结束后自动关闭

   *openSession没有和当前线程绑定,currentSession和当前线程绑定

2.如果使用currentSession需要在hibernate.cfg.xml文件中进行配置:

   *如果是本地事务(jdbc事务)

     <propertyname="hibernate.current_session_context_class">thread</property>

   *如果是全局事务(jta事务)

   <propertyname="hibernate.current_session_context_class">jta</property>

全局事务:资源管理器管理和协调的事务,可以跨越多个数据库和进程。资源管理器一般使用XA 二阶段提交协议与“企业信息系统”(EIS) 或数据库进行交互。

本地事务:在单个 EIS或数据库的本地并且限制在单个进程内的事务。本地事务不涉及多个数据来源。

原创粉丝点击