码迷,mamicode.com
首页 > 数据库 > 详细

JdbcTemplate使用事务

时间:2014-11-06 17:53:34      阅读:183      评论:0      收藏:0      [点我收藏+]

标签:io   ar   使用   java   for   sp   数据   on   cti   

public int excuteTrac() {
    int temp = 0; //  批插入 
    String sql1[] = new String[4];
    //向第一个表插入的语句
    sql1[0] = "insert into usermbo(USERNAME,age,PASSWORD) values(‘ 23  ‘,‘3‘,‘45‘)";
    sql1[1] = "insert into usermbo(USERNAME,age,PASSWORD) values(‘22  ‘,‘22‘,‘22‘)";
    sql1[2] = "insert into usermbo(USERNAME,age,PASSWORD) values(‘ 44  ‘,‘44‘,‘4‘)";
    sql1[3] = "insert into usermbo(USERNAME,age,PASSWORD) values(‘ 55  ‘,‘55‘,‘55‘)";
    String[] sql2 = new String[3];
    //向第二个表插入的语句
    sql2[0] = "insert into address(NO,NAME) values(‘21‘,‘33‘)";
    // 此条数据是错误数据 插入会出现异常
    sql2[1] = "insert into address(NO,NAME) values(‘ee‘,‘44‘)";
    sql2[2] = "insert into address(NO,NAME) values(‘44‘,‘44‘)";
		
    DefaultTransactionDefinition def = new DefaultTransactionDefinition();
    DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(jdbcTemplate.getDataSource());
    TransactionStatus status = transactionManager.getTransaction(def);
    try {
        int[] a = jdbcTemplate.batchUpdate(sql1);
        int[] b = jdbcTemplate.batchUpdate(sql2);
        for (int x : a) {
            System.out.println(x);
        }
        for (int x : b) {
            System.out.println(x);
        }
    } catch (Exception ex) {
        System.out.println("出现事务异常");
        // transactionManager.rollback(status);
        temp = -1;
    } finally {
        transactionManager.commit(status);
    }
    return temp;
}



JdbcTemplate使用事务

标签:io   ar   使用   java   for   sp   数据   on   cti   

原文地址:http://my.oschina.net/lhplj/blog/341555

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!