日期:2014-05-16  浏览次数:20422 次

JdbcTemplate的批量更新和插入方法
方法一:
private JdbcTemplate jdbcTemplate;
public int[] batchUpdate(final List<Actor> actors) {
  int[] updateCounts = jdbcTemplate.batchUpdate(
    "update t_actor set first_name = ?, last_name = ? where id = ?",
    new BatchPreparedStatementSetter() {
      public void setValues(PreparedStatement ps, int i) throws SQLException {
        ps.setString(1, actors.get(i).getFirstName());
        ps.setString(2, actors.get(i).getLastName());
        ps.setLong(3, actors.get(i).getId().longValue());
      }
      public int getBatchSize() {
        return actors.size();
      }
    }
  );
  return updateCounts;
}

方法二:
private SimpleJdbcTemplate simpleJdbcTemplate;
public int[] batchUpdate(final List<Actor> actors) {
  SqlParameterSource[] batch = SqlParameterSourceUtils.createBatch(actors.toArray());
  int[] updateCounts = simpleJdbcTemplate.batchUpdate(
    "update t_actor set first_name = :firstName, last_name = :lastName where id = :id",
    batch);
  return updateCounts;
}

方法三:
private SimpleJdbcTemplate simpleJdbcTemplate;
private SimpleJdbcInsert insertActor;
public void setDataSource(DataSource dataSource) {
  this.simpleJdbcTemplate = new SimpleJdbcTemplate(dataSource);
  this.insertActor = new SimpleJdbcInsert(dataSource).withTableName("t_actor");
}
public void add(Actor actor) {
  Map<String, Object> parameters = new HashMap<String, Object>(3);
  parameters.put("id", actor.getId());
  parameters.put("first_name", actor.getFirstName());
  parameters.put("last_name", actor.getLastName());
  insertActor.execute(parameters);
}

方法四:
private SimpleJdbcTemplate simpleJdbcTemplate;
private SimpleJdbcInsert insertActor;
public void setDataSource(DataSource dataSource) {
  this.simpleJdbcTemplate = new SimpleJdbcTemplate(dataSource);
  this.insertActor = new SimpleJdbcInsert(dataSource)
    .withTableName("t_actor");
    .usingGeneratedKeyColumns("id");
}
public void add(Actor actor) {
  Map<String, Object> parameters = new HashMap<String, Object>(2);
  parameters.put("id", actor.getId());
  parameters.put("first_name", actor.getFirstName());
  parameters.put("last_name", actor.getLastName());
  Number newId = insertActor.executeAndReturnKey(parameters);
  actor.setId(newId.longValue());
}