首页 > 编程 > Java > 正文

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

2019-11-26 09:17:41
字体:
来源:转载
供稿:网友

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

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了。可见这种效率很高。


数据库结果


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

批量新增数据记录完毕。

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

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表