问题
I use Spring-JDBC to insert the list of facebook friends for a user in my MySQL database.
I have a final Long that contains the user uid and a List that contains the list of his friends.
my query is:
final String sqlInsert="insert into fb_user_friends(fb_uid,friend_uid) values(?,?)";
I create batch parameters using SqlParameterSourceUtils
SqlParameterSource[] batch = SqlParameterSourceUtils.createBatch(friendsList.toArray());
and I execute the insert using:
int[] insertCounts = this._jdbcTemplate.batchUpdate(sqlInsert,batch);
the problem here that the list contains only the 2nd parameter that's required by the query.
do I have to modify the friendsList to add to it another column or is there another way?
thanks!
回答1:
This should help: http://static.springsource.org/spring/docs/3.0.x/reference/jdbc.html#jdbc-advanced-jdbc
EDIT:
final Long uid = 1L;
final List<Long> friendList /* = ... */;
int[] updateCounts = jdbcTemplate.batchUpdate(
"insert into fb_user_friends(fb_uid,friend_uid) values(?,?)",
new BatchPreparedStatementSetter() {
public void setValues(final PreparedStatement ps, final int i) throws SQLException {
ps.setLong(1, uid);
ps.setLong(2, friendList.get(i));
}
public int getBatchSize() {
return friendList.size();
}
});
OR
final List<User> userList /* = ... */;
SqlParameterSource[] batch = SqlParameterSourceUtils.createBatch(userList.toArray());
int[] updateCounts = simpleJdbcTemplate.batchUpdate(
"insert into fb_user_friends(fb_uid,friend_uid) values(:uid,:friendUid)",
batch);
with
@Data // from lombok
class User {
private Long uid;
private Long friendUid;
}
not tested, adapted from the provided link samples
来源:https://stackoverflow.com/questions/6402246/how-can-i-batchupdate-with-a-query-that-requires-2-parameters-and-only-one-of-th