Как я могу batchUpdate с запросом, который требует 2 параметра, и только один из них хранится в списке - PullRequest
0 голосов
/ 19 июня 2011

Я использую Spring-JDBC для вставки списка друзей на Facebook для пользователя в моей базе данных MySQL.

У меня есть окончательный Long, который содержит пользовательский uid и список, который содержит список его друзей.

мой запрос:

final String sqlInsert="insert into fb_user_friends(fb_uid,friend_uid) values(?,?)";

Я создаю параметры пакета, используя SqlParameterSourceUtils

SqlParameterSource[] batch = SqlParameterSourceUtils.createBatch(friendsList.toArray());

, и выполняю вставку, используя:

int[] insertCounts = this._jdbcTemplate.batchUpdate(sqlInsert,batch);

проблема здесь в том, что список содержит только 2-й параметр, который требуется для запроса.

мне нужно изменить список друзей, чтобы добавить в него другой столбец или есть другой способ?

спасибо!

1 Ответ

1 голос
/ 19 июня 2011

Это должно помочь: 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();
        }
});

ИЛИ

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);

с

@Data // from lombok 
class User {
    private Long uid;
    private Long friendUid;
}

не проверено, адаптировано из предоставленных образцов ссылок

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...