public int[] create(List<Notice> notices) { SqlParameterSource[] params = SqlParameterSourceUtils.createBatch(notices.toArray()); return jdbc.batchUpdate( "insert into notices (name, email, text) values (:name, :email, :text)", params); }
/** * 批量操作 * * @param sql * @param obj * @return */ public int[] batchOperate(String sql, List<?> obj) { int[] a = null; try { a = simpleJdbcTemplate.batchUpdate(sql, SqlParameterSourceUtils.createBatch(obj.toArray())); } catch (Exception e) { log.info(e); return null; // throw new DaoException("数据库操作失败!",e); } return a; }
private int[] batchUpdateByPojo(String sqlStr, List<Object> pojoList) { SqlParameterSource[] batch = SqlParameterSourceUtils.createBatch(pojoList.toArray()); int[] updateCounts = simpleJdbcTemplate.batchUpdate(sqlStr, batch); if (null != this.additiveSql) simpleJdbcTemplate.update(this.additiveSql); return updateCounts; }
public int batchUpdate( String sqlId, Map<String, Integer> sqlTypes, final List<Map<String, Object>> batchValues) { long cur = System.currentTimeMillis(); try { int[] batchCount = null; String sql = sqlp.getValue(sqlId, sqlId); ParsedSql parsedSql = NamedParameterUtils.parseSqlStatement(sql); if (sqlTypes != null && !sqlTypes.isEmpty()) { MapSqlParameterSource[] batch = new MapSqlParameterSource[batchValues.size()]; for (int i = 0; i < batchValues.size(); i++) { Map<String, Object> valueMap = batchValues.get(i); batch[i] = new MapSqlParameterSource(); for (Entry<String, Integer> entry : sqlTypes.entrySet()) { if (!valueMap.containsKey(entry.getKey())) { valueMap.put(entry.getKey(), null); } batch[i].addValue(entry.getKey(), valueMap.get(entry.getKey()), entry.getValue()); } if (logger.isTraceEnabled()) { logger.trace( new StringBuffer("SqlId=") .append(sqlp.containsKey(sqlId) ? sqlId : "") .append("\n#") .append((i + 1)) .append("\t") .append(CapDbUtil.convertToSQLCommand(sql, valueMap)) .toString()); } } cur = System.currentTimeMillis(); batchCount = NamedParameterBatchUpdateUtils.executeBatchUpdateWithNamedParameters( parsedSql, batch, super.getJdbcOperations()); } else { SqlParameterSource[] batch = SqlParameterSourceUtils.createBatch( batchValues.toArray(new HashMap[batchValues.size()])); cur = System.currentTimeMillis(); batchCount = NamedParameterBatchUpdateUtils.executeBatchUpdateWithNamedParameters( parsedSql, batch, super.getJdbcOperations()); } int rows = 0; for (int i : batchCount) { rows += i; } return rows; } catch (Exception e) { Throwable cause = (Throwable) e; String msg = cause.getMessage(); while ((cause = cause.getCause()) != null) { if (cause instanceof BatchUpdateException) { cause = ((BatchUpdateException) cause).getNextException(); } msg = cause.getMessage(); } throw new CapDBException(msg, e, causeClass); } finally { logger.info("CapNamedJdbcTemplate spend {} ms", (System.currentTimeMillis() - cur)); } } // ;