|
MyBatis实现批量操作
/**
* 批量操作
* @param sqlID
* @param bindParams
* @return
* @throws SQLException
*/
@SuppressWarnings("unchecked")
private <T> int[] batchUpdate(String sqlID, List<T> bindParams) throws SQLException
{
SqlSession sqlse = getSqlSession();
Connection connection = null;
Transaction transaction = null;
Environment env;
BatchExecutor be;
Configuration conf = sqlse.getConfiguration();
conf.setDefaultExecutorType(ExecutorType.BATCH);
env = conf.getEnvironment();
connection = env.getDataSource().getConnection();
connection.setAutoCommit(false);
transaction = env.getTransactionFactory().newTransaction(connection, false);
be = new BatchExecutor(conf, transaction);
MappedStatement ms = conf.getMappedStatement(sqlID);
int x = 0;
Object bt;
List<Object> bts = (List<Object>) bindParams;
for (int i = 0; i < bts.size(); i++) {
bt = bts.get(i);
x = be.update(ms, bt);
System.out.println(x + "x:");
}
be.commit(true);
transaction.commit();
List<BatchResult> bl = be.flushStatements();
int[] ret = null;
if(bl != null){
for(int b = 0; b < bl.size(); b ++){
BatchResult br = bl.get(b);
ret = br.getUpdateCounts();
System.out.println("re length:" + ret.length);
}
}
be.close(false);
transaction.close();
System.out.println(x);
return ret;
} |
|
|