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

后端 未结 1 575
情书的邮戳
情书的邮戳 2021-01-16 17:05

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

相关标签:
1条回答
  • 2021-01-16 17:10

    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 讨论(0)
提交回复
热议问题