* @param argsList
*/
@SuppressWarnings("unchecked")
protected <T extends Number> List<T> batchInsertWithIdReturn(final String sql, final List<Object[]> argsList) {
Assert.notEmpty(argsList, "args can not be empty while batch insert");
final KeyHolder keyHolder = new GeneratedKeyHolder();
jdbcTemplate.execute(new PreparedStatementCreator() {
@Override
public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
PreparedStatement ps = con.prepareStatement(sql, PreparedStatement.RETURN_GENERATED_KEYS);
return ps;
}
}, new PreparedStatementCallback<int[]>() {
private void setValues(PreparedStatement ps, int i) throws SQLException {
Object[] args = argsList.get(i);
int length = args.length;
for (int j = 1; j <= length; j++) {
ps.setObject(j, args[j - 1]);
}
}
private int[] processResult(PreparedStatement ps, int[] rows) throws SQLException {
List<Map<String, Object>> generatedKeys = keyHolder.getKeyList();
generatedKeys.clear();
ResultSet keys = ps.getGeneratedKeys();
if (keys != null) {
try {
RowMapperResultSetExtractor<Map<String, Object>> rse = new RowMapperResultSetExtractor<Map<String, Object>>(
new ColumnMapRowMapper(), rows.length);
generatedKeys.addAll(rse.extractData(keys));
} finally {
JdbcUtils.closeResultSet(keys);
}
}
return rows;
}
@Override
public int[] doInPreparedStatement(PreparedStatement ps) throws SQLException, DataAccessException {
int batchSize = argsList.size();
if (JdbcUtils.supportsBatchUpdates(ps.getConnection())) {
for (int i = 0; i < batchSize; i++) {
setValues(ps, i);
ps.addBatch();
}
int[] rows = ps.executeBatch();
return processResult(ps, rows);
} else {
List<Integer> rowsAffected = new ArrayList<Integer>();
for (int i = 0; i < batchSize; i++) {
setValues(ps, i);
rowsAffected.add(ps.executeUpdate());
}
int[] rowsAffectedArray = new int[rowsAffected.size()];
for (int i = 0; i < rowsAffectedArray.length; i++) {
rowsAffectedArray[i] = rowsAffected.get(i);
}
return processResult(ps, rowsAffectedArray);
}
}
});
List<T> keys = new ArrayList<T>(argsList.size());
List<Map<String, Object>> generatedKeys = keyHolder.getKeyList();
int length = generatedKeys.size();
for (int i = 0; i < length; i++) {
Iterator<Object> keyIter = generatedKeys.get(i).values().iterator();
if (keyIter.hasNext()) {
Object key = keyIter.next();