首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > J2EE开发 >

hibernate 事务如何管理

2012-04-06 
hibernate 事务怎么管理最近在学习用struts+hibernate3开发,可是事务不知道怎么管理,老师上课讲java更是没

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 ");  


                }  
                return   forward;  
        }  


  可是像思路2这样做,感觉事务管理粒度太大了,不很好,可是不知道其他的方法,大家可以指点一下小弟不!

不甚感激!!!!!

[解决办法]
第一种不是很好吗?
[解决办法]
你可以看看spring的声明式事务啊
[解决办法]

探讨
引用:

第一种不是很好吗?

那样感觉太麻烦了,每次都要重复

[解决办法]
自己写个方法,模拟spring声明式事务
[解决办法]
看看spring的声明式事务

热点排行