当前位置: 移动技术网 > IT编程>开发语言>Java > mybatis学习之路mysql批量新增数据的方法

mybatis学习之路mysql批量新增数据的方法

2019年07月19日  | 移动技术网IT编程  | 我要评论

汶上县人民政府,魔神艳游,义乌汽车站

接下来两节要探讨的是批量插入和批量更新,因为这两种操作在企业中也经常用到。

mysql新增语句  

insert into 表名(字段,字段。。。) values ( 值,值 。。。);此种适合单条插入。

批量插入,一种可以在代码中循环着执行上面的语句,但是这种效率太差,下面会有对比,看看它有多差。

另一种,可以用mysql支持的批量插入语句,

insert into 表名(字段,字段。。。) values ( 值,值 。。。),( 值,值 。。。),( 值,值 。。。)....

这种方式相比起来,更高效。

下面开始来实现。

 <!-- 跟普通的insert没有什么不同的地方 ,主要用来跟下面的批量插入做对比。-->
  <insert id="insert" parametertype="com.soft.mybatis.model.customer">
    <!-- 跟自增主键方式相比,这里的不同之处只有两点
          1 insert语句需要写id字段了,并且 values里面也不能省略
          2 selectkey 的order属性需要写成before 因为这样才能将生成的uuid主键放入到model中,
          这样后面的insert的values里面的id才不会获取为空
       跟自增主键相比就这点区别,当然了这里的获取主键id的方式为 select uuid()
       当然也可以另写别生成函数。-->
    <selectkey keyproperty="id" order="before" resulttype="string">
      select uuid()
    </selectkey>
    insert into t_customer (id,c_name,c_sex,c_cerono,c_cerotype,c_age)
    values (#{id},#{name},#{sex},#{cerono},#{cerotype},#{age})
  </insert>
 
  <!-- 批量插入, -->
  <insert id="batchinsert" parametertype="java.util.map">
    <!-- 这里只做演示用,真正项目中不会写的这么简单。 -->
    insert into
     t_customer (id,c_name,c_sex,c_cerono,c_cerotype,c_age)
    values
    <!-- foreach mybatis循环集合用的
       collection="list" 接收的map集合中的key 用以循环key对应的属性
         separator="," 表示每次循环完毕,在sql后面放一个逗号
         item="cus" 每次循环的实体对象 名称随意-->
    <foreach collection="list" separator="," item="cus">
      <!-- 组装values对象,因为这张表的主键为非自增主键,所以这里 (select uuid()) 用于生成id的值-->
      ((select uuid()),#{cus.name},#{cus.sex},#{cus.cerono},#{cus.cerotype},#{cus.age})
    </foreach>
  </insert>

实体model对象

package com.soft.mybatis.model;
 
/**
 * created by xuweiwei on 2017/9/10.
 */
public class customer {
 
  private string id;
  private string name;
  private integer age;
  private integer sex;
  private string cerono;
  private integer cerotype;
 
  public string getid() {
    return id;
  }
 
  public void setid(string id) {
    this.id = id;
  }
 
  public string getname() {
    return name;
  }
 
  public void setname(string name) {
    this.name = name;
  }
 
  public integer getage() {
    return age;
  }
 
  public void setage(integer age) {
    this.age = age;
  }
 
  public integer getsex() {
    return sex;
  }
 
  public void setsex(integer sex) {
    this.sex = sex;
  }
 
  public string getcerono() {
    return cerono;
  }
 
  public void setcerono(string cerono) {
    this.cerono = cerono;
  }
 
  public integer getcerotype() {
    return cerotype;
  }
 
  public void setcerotype(integer cerotype) {
    this.cerotype = cerotype;
  }
 
  @override
  public string tostring() {
    return "customer{" +
        "id='" + id + '\'' +
        ", name='" + name + '\'' +
        ", age=" + age +
        ", sex=" + sex +
        ", cerono='" + cerono + '\'' +
        ", cerotype='" + cerotype + '\'' +
        '}';
  }
}

接口

int add(customer customer);
int batchinsert(map<string,object> param);

实现

 /**
   * 新增数据
   * @param customer
   * @return
   */
  public int add(customer customer) {
    return insert("customer.insert", customer);
  }
 
  /**
   * 批量插入数据
   * @param param
   * @return
   */
  public int batchinsert(map<string,object> param) {
    return insert("customer.batchinsert", param);
  }
 
  /**
   * 公共部分
   * @param statementid
   * @param obj
   * @return
   */
  private int insert(string statementid, object obj){
    sqlsession sqlsession = null;
    try {
      sqlsession = sqlsessionutil.getsqlsession();
      int key = sqlsession.insert(statementid, obj);
      // commit
      sqlsession.commit();
      return key;
    } catch (exception e) {
      sqlsession.rollback();
      e.printstacktrace();
    } finally {
      sqlsessionutil.closesession(sqlsession);
    }
    return 0;
  }

测试类

 @test
  public void add() throws exception {
    long start = system.currenttimemillis();
    for(int i=0;i<1000;i++){
      customer customer = new customer();
      customer.setname("普通一条条插入 "+ i);
      customer.setage(15);
      customer.setcerono("000000000000"+ i);
      customer.setcerotype(2);
      customer.setsex(1);
      int result = customerdao.add(customer);
    }
    system.out.println("耗时 : "+(system.currenttimemillis() - start));
  }
 
  @test
  public void batchinsert() throws exception {
    map<string,object> param = new hashmap<string,object>();
    list<customer> list = new arraylist<customer>();
    for(int i=0;i<1000;i++){
      customer customer = new customer();
      customer.setname("批量插入" + i);
      customer.setage(15);
      customer.setcerono("111111111111"+i);
      customer.setcerotype(2);
      customer.setsex(1);
      list.add(customer);
    }
    param.put("list",list);
    long start = system.currenttimemillis();
    int result = customerdao.batchinsert(param);
    system.out.println("耗时 : "+(system.currenttimemillis() - start));
  }

两种都进行插入1000条测试

由于我没有用连接池等等原因,在插入了700多条的时候 junit直接挂了,

cause: org.apache.ibatis.executor.executorexception: error selecting key or setting result to parameter object.

cause: com.mysql.jdbc.exceptions.jdbc4.mysqlnontransientconnectionexception:

data source rejected establishment of connection,  message from server: "too many connections"


数据库插入结果:


但是第二种仅仅用了2秒多就ok了。可见这种效率很高。


数据库结果


这里写了两个,其实第一种仅仅是做对比效率用。

批量新增数据记录完毕。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网