JdbcTemplate使用事务控制批处理

//在dao中写的一个方法
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;
}

标签