隨筆-112  評論-73  文章-0  trackbacks-0
          groovy sql 事務(wù)
          def init = { servletContext -> Sql.metaClass.withTransaction = { Closure stmt -> cacheConnection(){ connection.autoCommit = false try { stmt().each { execute(it.query, it.params) } connection.commit() } catch ( e) { connection.rollback() throw e } finally { connection.autoCommit = true } } } } def destroy = { } } Then, you may invoke it in a service: def sql = new Sql(dataSource) Connection connection = sql.createConnection(); try{ def sql2 = new Sql(connection); sql2.withTransaction { [ [query:"insert into table values (?,?,?)", params:[p1, p2, p3]], [query:"insert into table2 values (?,?,?)", params:[p4, p5, p6]] ] } }finally{ if(sql.dataSource){ connection.close(); } } There is already a JIRA requesting this to be added to Groovy: http://jira.codehaus.org/browse/GROOVY-3158. Vote it if you find this useful.


          public void ttt(){
          Sql.metaClass.useTransaction = { Closure closure ->
          java.sql.Connection conn = null
          try { conn = createConnection();
          conn.autoCommit = false;
          Sql sql2 = new Sql( conn );
          closure(sql2);
          conn.commit();
          } catch (e) {
          if(conn != null)
          conn.rollback();
          e.printStackTrace();
          throw e
          } finally {
          if ( conn != null ) {
          conn.autoCommit = true
          if ( dataSource ) { conn.close()
          }
          }
          }
          }
          }




          posted on 2009-12-18 19:53 Libo 閱讀(977) 評論(0)  編輯  收藏

          只有注冊用戶登錄后才能發(fā)表評論。


          網(wǎng)站導(dǎo)航:
           
          主站蜘蛛池模板: 孟村| 伊川县| 荔浦县| 周宁县| 娱乐| 鹿泉市| 洪泽县| 连城县| 清河县| 河西区| 民乐县| 临夏县| 高青县| 奈曼旗| 喀喇沁旗| 景东| 汕尾市| 晋城| 新昌县| 永登县| 深州市| 随州市| 固原市| 土默特右旗| 瑞安市| 边坝县| 临潭县| 兴隆县| 泽州县| 孝义市| 临城县| 铁岭市| 凌海市| 阿坝| 车致| 平塘县| 天峨县| 平和县| 保德县| 江口县| 长泰县|