如何使用需要2个参数的查询进行batchUpdate,并且只有其中一个存储在列表中 [英] how can I batchUpdate with a query that requires 2 parameters and only one of them is stored in a list

查看:151
本文介绍了如何使用需要2个参数的查询进行batchUpdate,并且只有其中一个存储在列表中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用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?

谢谢!

推荐答案

这应该有所帮助: http://static.springsource.org/spring/docs/3.0.x/reference/jdbc.html#jdbc-advanced-jdbc

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,并且只有其中一个存储在列表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆