问题描述
我使用Spring-JDBC在我的MySQL数据库中为用户插入facebook好友列表。
I use Spring-JDBC to insert the list of facebook friends for a user in my MySQL database.
我有一个包含用户uid和a的最终Long列表包含他的朋友列表。
I have a final Long that contains the user uid and a List that contains the list of his friends.
我的查询是:
final String sqlInsert="insert into fb_user_friends(fb_uid,friend_uid) values(?,?)";
我使用SqlParameterSourceUtils创建批处理参数
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.
我是否必须修改friendsList以将其添加到另一列或是否有其他方式?
do I have to modify the friendsList to add to it another column or is there another way?
谢谢!
推荐答案
这应该有所帮助:
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;
}
未经测试,改编自提供的链接样本
这篇关于如何使用需要2个参数的查询进行batchUpdate,并且只有其中一个存储在列表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!