JdbcTemplate使用事务

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;
}



郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。