日期:2014-05-20  浏览次数:20821 次

hibernate 事务怎么管理
最近在学习用   struts   +   hibernate3开发,可是事务不知道怎么管理,老师上课讲java   更是没有说这些内容,很是郁闷,现在自己有两个思路

1.
        session   session   =   sessionFactory.openSession();
        Transaction   tx   =   session.beginTransaction();
     
.....
     
        tx.commit();
      session.close();

2.把DAO中所有事务处理相关的代码去掉,包括关闭hibernate   session   的代码。  
由于Action太多,当初的开发人员也找不回来了,如果在所有的Action中添加事务处理的代码的话,粒度和位置都不好控制。于是做了一个统一处理所有Action中事务的尝试,大体思路如下:  

扩展struts   的   RequestProcessor类,重写processActionPerform方法在Action执行前启动事务,执行成功后提交事务,执行中发生异常回滚事务,代码片段如下:  

@Override  
        protected   ActionForward   processActionPerform(HttpServletRequest   request,  
                        HttpServletResponse   response,   Action   action,   ActionForm   form,   ActionMapping   mapping)  
                        throws   IOException,   ServletException   {  
                Transaction   tx   =   HibernateSessionFactory.getSession().beginTransaction();  
                ActionForward   forward   =   null;  
                try   {  
                        log.info( "begin   transaction   in   HibernateSessionRequestProcessor ");  
                        log.info( "before   action   execute ");  
                        forward   =   super.processActionPerform(request,   response,   action,   form,   mapping);  
                        log.info( "after   action   execute ");  
                        tx.commit();  
                             
                }   catch   (Exception   e)   {  
                        tx.rollback();  
                        log.info( "exception   rollback   transaction   HibernateSessionRequestProcessor ");  
                        request.setAttribute( "error ",   "执行出现错误了 ");  
                        return   mapping.findForward( "error ");  
                }   finally   {  
                        HibernateSessionFactory.closeSession();  
                        log.info( "close   session   in   HibernateSessionRequestProcessor ");