开发者

how can I batchUpdate with a query that requires 2 parameters and only one of them is stored in a list

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 sqlI开发者_Go百科nsert="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!


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜