iBATIS批量插入数据到数据库

时间:2022-12-15 21:42:07

批量插入数据方法实现:

/**
  * ibatis批量插入数据
  * @param recordList
  */
  public void insertRecordByList(final List<Record> recordList) {
    this.getSqlMapClientTemplate().execute(new SqlMapClientCallback() {
      public Object doInSqlMapClient(SqlMapExecutor executor)
          throws SQLException {
        executor.startBatch();
        // 每次提交最大条数
        final int batchSize = 200;
        int count = 0;
        for (Record record : recordList) {
          executor.insert("Record.insertRecord", record);
          // 每200条数据提交一次
          if (++count % batchSize == 0) {
            executor.executeBatch();
          }
        }
        // 提交剩余的数据
        executor.executeBatch();
        return null;
      }
    });
  }

对应的sqlMap:

<sqlMap namespace="Record">
  <typeAlias alias="record" type="me.gogogogo.domain.Record" />

  <insert id="insertRecord"  parameterClass="record">
    insert into record
      (id, 
      record, 
      insetDate) 
    values 
      (sequence_record.nextval, 
      #record#, 
      sysdate)
  </insert>
</sqlMap>