java中Spring jdbc批量儲存資料例子

來源:互聯網
上載者:User

資料list:list.add(bcHistory);

批量插入:

 代碼如下 複製代碼

try {
    jt.batchUpdate(
    "insert into b_chat_history (id,from_phone,from_user,to_phone,to_user,type,msg,url,thumb,length,timestamp) value (?,?,?,?,?,?,?,?,?,?,?)",
    new BatchPreparedStatementSetter() {
        public void setValues(PreparedStatement ps, int i)throws SQLException {
            ps.setString(1, UUID.randomUUID().toString());// ID的值
            ps.setString(2, list.get(i).getFrom_phone());
            ps.setString(3, list.get(i).getFrom_user());
            ps.setString(4, list.get(i).getTo_phone());
            ps.setString(5, list.get(i).getTo_user());
            ps.setString(6, list.get(i).getType());
            ps.setString(7, list.get(i).getMsg());
            ps.setString(8, list.get(i).getUrl());
                ps.setString(9, list.get(i).getThumb());
            ps.setInt(10,list.get(i).getLength());
            ps.setTimestamp(11, list.get(i).getTimestamp());
        }
 
public int getBatchSize() {
    return list.size();
    }
     });
} catch (Exception e2) {
    System.out.println("可能有資料異常,同步部分資料異常");
    e2.printStackTrace();
}


補充:

使用JDBCTemplate 進行基本的大量操作

這種方法是網上大多數採用的方法, 但是在實際應用中我感覺不太方便,這個方法能不能做成一個通用的介面呢?一直沒有仔細研究過

  

 代碼如下 複製代碼

 

public class JdbcActorDao implements ActorDao {
  private JdbcTemplate jdbcTemplate;

  public void setDataSource(DataSource dataSource) {
    this.jdbcTemplate = new JdbcTemplate(dataSource);
  }

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

  // ... additional methods
}

二、 使用List集合形式的參數的大量操作

    如果使用List集合來進行大量操作,這種方法是比較合適的,spring jdbc core 包中提供了一個SqlParamterSource 對象,然後使用

 代碼如下 複製代碼

SqlParameterSourceUtils.createBatch
這個方法,把javabean的list  轉化成array,spring會迴圈的進行取值;

public class JdbcActorDao implements ActorDao {
  private NamedParameterTemplate namedParameterJdbcTemplate;

  public void setDataSource(DataSource dataSource) {
    this.namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(dataSource);
  }

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

  // ... additional methods
}

當然,你還可以使用類似的方法來進行大量操作,如下代碼:(代碼來自官方網站樣本)

 代碼如下 複製代碼

public class JdbcActorDao implements ActorDao {

  private JdbcTemplate jdbcTemplate;

  public void setDataSource(DataSource dataSource) {
    this.jdbcTemplate = new JdbcTemplate(dataSource);
  }

  public int[] batchUpdate(final List<Actor> actors) {
    List<Object[]> batch = new ArrayList<Object[]>();
    for (Actor actor : actors) {
      Object[] values = new Object[] {
          actor.getFirstName(),
          actor.getLastName(),
          actor.getId()};
      batch.add(values);
    }
    int[] updateCounts = jdbcTemplate.batchUpdate(
        "update t_actor set first_name = ?, last_name = ? where id = ?",
        batch);
    return updateCounts;
  }

  // ... additional methods

}

三、使用多維陣列進行大量操作

 代碼如下 複製代碼

public class JdbcActorDao implements ActorDao {

  private JdbcTemplate jdbcTemplate;

  public void setDataSource(DataSource dataSource) {
    this.jdbcTemplate = new JdbcTemplate(dataSource);
  }

  public int[][] batchUpdate(final Collection<Actor> actors) {
    int[][] updateCounts = jdbcTemplate.batchUpdate(
        "update t_actor set first_name = ?, last_name = ? where id = ?",
        actors,
        100,
        new ParameterizedPreparedStatementSetter<Actor>() {
          public void setValues(PreparedStatement ps, Actor argument) throws SQLException {
            ps.setString(1, argument.getFirstName());
            ps.setString(2, argument.getLastName());
            ps.setLong(3, argument.getId().longValue());
          }
        });
    return updateCounts;
  }

  // ... additional methods

}

上面的代碼中,100表示一次大量操作的容量;

四、使用SimpleJdbcInsert 來進行簡單的插入操作

    一般的,我們會使用update來進行插入操作,但是spring提供了更加簡潔物件導向插入方法:

 代碼如下 複製代碼

public class JdbcActorDao implements ActorDao {

  private JdbcTemplate jdbcTemplate;
  private SimpleJdbcInsert insertActor;

  public void setDataSource(DataSource dataSource) {
    this.jdbcTemplate = new JdbcTemplate(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);
  }

  // ... additional methods
}

如果我們需要得到插入的傳回值呢?

 代碼如下 複製代碼

public class JdbcActorDao implements ActorDao {

  private JdbcTemplate jdbcTemplate;
  private SimpleJdbcInsert insertActor;

  public void setDataSource(DataSource dataSource) {
    this.jdbcTemplate = new JdbcTemplate(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("first_name", actor.getFirstName());
    parameters.put("last_name", actor.getLastName());
    Number newId = insertActor.executeAndReturnKey(parameters);
    actor.setId(newId.longValue());
  }

  // ... additional methods
}

注意了,此處使用了一個map作為參數,欄位名作為鍵,所以我們可以根據傳入的對象來自動去擷取參數名及參數值的map,提示:可以利用反射原來處理:

範例程式碼:

 代碼如下 複製代碼
/**
   * 擷取名稱值的map
   * @param class1
   * @return
   */
  public static <M> SqlParameterSource getParamsMap(M bean) {
    if(bean==null)return null;
    MapSqlParameterSource parameters = new MapSqlParameterSource();
    Class<?> _class = bean.getClass();
    Table _table = _class.getAnnotation(Table.class);
    if(_table==null){
      logger.error(_class.getName()+" not find @Table value!please check it!");
      throw(new NotFoundTableAnnotaionException(_class.getName()+" not find @Table value!please check it!"));
    }
    String primaryKey=_table.primaryKey();
    Field[] allFields=getAllFields(_class);
    Object _primaryKeyValue="";
    for (Field field : allFields) {
      if(Modifier.isStatic(field.getModifiers()))continue;
      field.setAccessible(true);
      try {
        if(StringUtil.isEqual(primaryKey, field.getName())){
          _primaryKeyValue=field.get(bean);
          continue;
        }
        parameters.addValue(field.getName(), field.get(bean));
      } catch (IllegalArgumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } catch (IllegalAccessException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
    return parameters;
  }

提出一個問題:如果我的欄位名及資料庫的欄位名不一樣咋辦?

解決辦法:

 代碼如下 複製代碼

public class JdbcActorDao implements ActorDao {

  private JdbcTemplate jdbcTemplate;
  private SimpleJdbcInsert insertActor;

  public void setDataSource(DataSource dataSource) {
    this.jdbcTemplate = new JdbcTemplate(dataSource);
    this.insertActor = new SimpleJdbcInsert(dataSource)
        .withTableName("t_actor")
        .usingColumns("first_name", "last_name")
        .usingGeneratedKeyColumns("id");
  }

  public void add(Actor actor) {
    Map<String, Object> parameters = new HashMap<String, Object>(2);
    parameters.put("first_name", actor.getFirstName());
    parameters.put("last_name", actor.getLastName());
    Number newId = insertActor.executeAndReturnKey(parameters);
    actor.setId(newId.longValue());
  }

  // ... additional methods

}
usingColumns("first_name", "last_name") //主要是這句話~

當然,也可以使用我們之前提到過的, SqlParameterSource parameters = new   MapSqlParameterSource();而且可以進行鏈式操作。

 代碼如下 複製代碼

public class JdbcActorDao implements ActorDao {

  private JdbcTemplate jdbcTemplate;
  private SimpleJdbcInsert insertActor;

  public void setDataSource(DataSource dataSource) {
    this.jdbcTemplate = new JdbcTemplate(dataSource);
    this.insertActor = new SimpleJdbcInsert(dataSource)
        .withTableName("t_actor")
        .usingGeneratedKeyColumns("id");
  }

  public void add(Actor actor) {
    SqlParameterSource parameters = new MapSqlParameterSource()
        .addValue("first_name", actor.getFirstName())
        .addValue("last_name", actor.getLastName());
    Number newId = insertActor.executeAndReturnKey(parameters);
    actor.setId(newId.longValue());
  }

  // ... additional methods

}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.