我使用spring BatchSqlUpdate插入一组行。如何为插入的所有行获取自动生成的密钥?
进行单次插入时,我得到了这样的键 -
SqlUpdate sqlUpdate = new SqlUpdate(dataSource, sqlTemplate.toString());
sqlUpdate.setReturnGeneratedKeys(true);
KeyHolder keyHolder = new GeneratedKeyHolder();
sqlUpdate.update(new Object[] {}, keyHolder);
return keyHolder.getKey().longValue();
谢谢!
答案 0 :(得分:5)
模板proc类:
public abstract class BatchPreparedStatementSetterWithKeyHolder<T> implements BatchPreparedStatementSetter {
private final List<T> beans;
/**
* @param datas
* @param returnGeneratedKeys true设置{@linkplain Statement#RETURN_GENERATED_KEYS}
*/
public BatchPreparedStatementSetterWithKeyHolder(List<T> beans) {
this.beans = beans;
}
@Override
public void setValues(PreparedStatement ps, int i) throws SQLException {
setValues(ps, beans.get(i));
}
@Override
public final int getBatchSize() {
return beans.size();
}
public void setPrimaryKey(KeyHolder keyHolder) {
List<Map<String, Object>> keys = keyHolder.getKeyList();
for (int i = 0, len = keys.size(); i < len; i++) {
setPrimaryKey(keys.get(i), beans.get(i));
}
}
protected abstract void setValues(PreparedStatement ps, T bean) throws SQLException;
protected abstract void setPrimaryKey(Map<String, Object> primaryKey, T bean);
}
一个util方法batchupdate:
private static void generatedKeys(PreparedStatement ps, KeyHolder keyHolder) throws SQLException {
List<Map<String, Object>> keys = keyHolder.getKeyList();
ResultSet rs = ps.getGeneratedKeys();
if (rs == null) return;
try {
keys.addAll(new RowMapperResultSetExtractor<Map<String, Object>>(new ColumnMapRowMapper(), 1).extractData(rs));
} finally {
UtilIO.close(rs);
}
}
/**
* 批量更新
* @param jdbcTemplate
* @param sql
* @param pss
* @param keyHolder 存储主键,如果要存储主键,就必须传入此对象
* @return sql执行结果
* @see JdbcTemplate#batchUpdate(String, org.springframework.jdbc.core.BatchPreparedStatementSetter)
*/
public static <T> int[] batchUpdateWithKeyHolder(JdbcTemplate jdbcTemplate, final String sql, final BatchPreparedStatementSetterWithKeyHolder<T> pss) {
return jdbcTemplate.execute(new PreparedStatementCreator() {
@Override
public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
return con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
}
}, new PreparedStatementCallback<int[]>() {
@Override
public int[] doInPreparedStatement(PreparedStatement ps) throws SQLException, DataAccessException {
try {
int batchSize = pss.getBatchSize();
InterruptibleBatchPreparedStatementSetter ipss =
(pss instanceof InterruptibleBatchPreparedStatementSetter ?
(InterruptibleBatchPreparedStatementSetter) pss : null);
int[] result;
KeyHolder keyHolder = new GeneratedKeyHolder();
try {
if (JdbcUtils.supportsBatchUpdates(ps.getConnection())) {
for (int i = 0; i < batchSize; i++) {
pss.setValues(ps, i);
if (ipss != null && ipss.isBatchExhausted(i)) break;
ps.addBatch();
}
result = ps.executeBatch();
generatedKeys(ps, keyHolder);
} else {
List<Integer> rowsAffected = new ArrayList<Integer>();
for (int i = 0; i < batchSize; i++) {
pss.setValues(ps, i);
if (ipss != null && ipss.isBatchExhausted(i)) break;
rowsAffected.add(ps.executeUpdate());
generatedKeys(ps, keyHolder);
}
result = UtilObj.tointArray(rowsAffected);
}
} finally {
pss.setPrimaryKey(keyHolder);
}
return result;
} finally {
if (pss instanceof ParameterDisposer) ((ParameterDisposer) pss).cleanupParameters();
}
}
});
}
e.x:
UtilJdbc.batchUpdateWithKeyHolder(jdbcTemplate,
"insert into tbe_vm_node (creator_id, host, ssh_ip, ssh_user, ssh_passwd)" +
" values (?, ?, ?, ?, ?)",
new BatchPreparedStatementSetterWithKeyHolder<VmNode>(vmNodes) {
@Override
protected void setValues(PreparedStatement ps, VmNode vmNode) throws SQLException {
UtilJdbc.setValues(ps, vmNode.getCreatorId(), vmNode.getHost(),
vmNode.getSshIp(), vmNode.getSshUser(), vmNode.getSshPasswd());
}
@Override
protected void setPrimaryKey(Map<String, Object> primaryKey, VmNode vmNode) {
vmNode.setId((Long) primaryKey.get("abc"));
}
});
答案 1 :(得分:0)
简单回答:使用getKeyList()方法
KeyHolder keyHolder = new GeneratedKeyHolder();
// Specify which column IDs to return, or get all columns by default
jdbcTemplate.update(INSERT_SQL, new MapSqlParameterSource(), keyHolder, new String[] {"column_name"});
List<Map<String, Object>> keyList = keyHolder.getKeyList();
答案 2 :(得分:0)
KeyHolder keyHolder = new GeneratedKeyHolder();
BatchSqlUpdate updateBatch = new BatchSqlUpdate();
updateBatch.setSql("Some INSERT SQL");
updateBatch.setJdbcTemplate(jdbcTemp);
updateBatch.setReturnGeneratedKeys(true);
updateBatch.updateByNamedParam( paramsMap ,keyHolder);
updateBatch.flush();
答案 3 :(得分:0)
感谢提供的解决方案,我实现了这一点,并且效果很好。但是,您引用了私有类(UtilIo,UtilObj),在这些类中我不得不解释您在做什么。我替换为“ UtilIO.close(rs);”与:
if (rs != null) {
rs.close();
}
然后我替换为“结果= UtilObj.tointArray(rowsAffected);”这段Java 8代码:
result = rowsAffected.stream().mapToInt(Integer::intValue).toArray();
答案 4 :(得分:-1)
据我所知,目前还没有使用BatchSqlUpdate
为此提供解决方案,但您始终可以