知识点:mybatis中,批量保存的两种方式

1.使用mybatis foreach标签

2.mybatis ExecutorType.BATCH

参考博客:https://www.jb51.net/article/91951.htm

一:使用mybatis foreach标签

具体用法如下:

<!-- 批量保存(foreach插入多条数据两种方法)
       int addEmpsBatch(@Param("emps") List<Employee> emps); -->
     <!-- MySQL下批量保存,可以foreach遍历 mysql支持values(),(),()语法 --> //推荐使用
     <insert id="addEmpsBatch">
      INSERT INTO emp(ename,gender,email,did)
      VALUES
      <foreach collection="emps" item="emp" separator=",">
      (#{emp.eName},#{emp.gender},#{emp.email},#{emp.dept.id})
      </foreach>
     </insert>
    
     <!-- 这种方式需要数据库连接属性allowMutiQueries=true的支持 -->  //在jdbc.url=jdbc:mysql://localhost:3306/mybatis?allowMultiQueries=true
  
 <!--  <insert
id="addEmpsBatch">                                                                                                                 后加上allowMultiQueries=true
       <foreach collection="emps" item="emp" separator=";">                                                                        表示可以多次执行insert into语句,中间;不会错
         INSERT INTO emp(ename,gender,email,did)
         VALUES(#{emp.eName},#{emp.gender},#{emp.email},#{emp.dept.id})
      </foreach>
     </insert> -->

二:mybatis ExecutorType.BATCH

Mybatis内置的ExecutorType有3种,默认为simple,该模式下它为每个语句的执行创建一个新的预处理语句,单条提交sql;而batch模式重复使用已经预处理的语句,并且批量执行所有更新语句,显然batch性能将更优; 但batch模式也有自己的问题,比如在Insert操作时,在事务没有提交之前,是没有办法获取到自增的id,这在某型情形下是不符合业务要求的

具体用法如下:

@Test  //批量保存方法测试
    public void testBatch() throws IOException{
        SqlSessionFactory sqlSessionFactory=getSqlSessionFactory();
        //可以执行批量操作的sqlSession
        SqlSession openSession=sqlSessionFactory.openSession(ExecutorType.BATCH);
        
        //批量保存执行前时间
        long start=System.currentTimeMillis();
        try{
        EmployeeMapper mapper=    openSession.getMapper(EmployeeMapper.class);
        for (int i = 0; i < 1000; i++) {
            mapper.addEmp(new Employee(UUID.randomUUID().toString().substring(0,5),"b","1"));
        }    
        
         openSession.commit();
        long end=  System.currentTimeMillis();
        //批量保存执行后的时间
        System.out.println("执行时长"+(end-start));
        //批量 预编译sql一次==》设置参数==》10000次==》执行1次   677
        //非批量  (预编译=设置参数=执行 )==》10000次   1121
        
        }finally{
            openSession.close();
        }
    }

mapper和mapper.xml如下:

public interface EmployeeMapper {   
    //批量保存员工
    public Long addEmp(Employee employee);

}

<mapper namespace="com.agesun.mybatis.dao.EmployeeMapper"
     <!--批量保存员工 -->
    <insert id="addEmp">
        insert into employee(lastName,email,gender)
        values(#{lastName},#{email},#{gender})
    </insert>
</mapper>

三:补充:mybatis ExecutorType.BATCH 在SSM框架中的用法

(1)在全局配置文件applcationContext.xml中加入

<!-- 配置一个可以批量执行的sqlSession -->
        <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
            <constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"></constructor-arg>
             <constructor-arg name="executorType" value="BATCH"></constructor-arg>
         </bean>

(2)在serviceImpl中加入

@Autowired
    private SqlSession sqlSession;

//批量保存员工
    @Override
    public Integer batchEmp() {
        // TODO Auto-generated method stub
    
            //批量保存执行前时间
            long start=System.currentTimeMillis();
    
            EmployeeMapper mapper=    sqlSession.getMapper(EmployeeMapper.class);
            for (int i = 0; i < 10000; i++) {
                mapper.addEmp(new Employee(UUID.randomUUID().toString().substring(0,5),"b","1"));
    
            }
            long end=  System.currentTimeMillis();
            long time2= end-start;
            //批量保存执行后的时间
            System.out.println("执行时长"+time2);
            
          
        return (int) time2;
        
    }

mybatis批量保存的两种方式(高效插入)的更多相关文章

  1. mybatis中批量插入的两种方式(高效插入)

    MyBatis简介 MyBatis是一个支持普通SQL查询,存储过程和高级映射的优秀持久层框架.MyBatis消除了几乎所有的JDBC代码和参数的手工设置以及对结果集的检索封装.MyBatis可以使用 ...

  2. mysql批量更新的两种方式效率试验<二>

    Mysql两种批量更新的对比 简介: mysql搭载mybits框架批量更新有两种方式,一种是在xml中循环整个update语句,中间以‘:’隔开,还有一种是使用case when 变相实现批量更新, ...

  3. MyBatis配置数据源的两种方式

    ---------------------siwuxie095                                     MyBatis 配置数据源的两种方式         1.配置方 ...

  4. MyBatis获取参数值的两种方式

    MyBatis获取参数值的两种方式:${}和#{} ${}的本质就是字符串拼接,#{}的本质就是占位符赋值 ${}使用字符串拼接的方式拼接sql,若为字符串类型或日期类型的字段进行赋值时,需要手动加单 ...

  5. mybatis批量更新的两种实现方式

    mapper.xml文件,后台传入一个对象集合,另外如果是mysql数据库,一点在配置文件上加上&allowMultiQueries=true,这样才可以执行多条sql,以下为mysql: & ...

  6. mybatis调用存储过程的两种方式

    先总结和说明一下注意点: 1.如果传入的某个参数可能为空,必须指定jdbcType 2.当传入map作为参数时,必须指定JavaType 3.如果做动态查询(参数为表名,sql关键词),可以使用${} ...

  7. 数据库链接 mybatis spring data jpa 两种方式

    jdbc mybatis                     spring data jpa dao service webservice jaxrs     jaxws  springmvc w ...

  8. Mybatis Dao开发的两种方式(一)

     原始Dao的开发方式: 1.创建数据库配置文件db.properties jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localh ...

  9. SpringBoot+MybatisPlus实现批量添加的两种方式

    第一种: 因为Mysql数据每次发送sql语句的长度不能超过1M,所以,每次发送insert语句以固定长度发送: 将sql语句在provider中,以固定长度装入List集合中,然后返回service ...

随机推荐

  1. wordpress 忘记密码

    update wp_users set user_pass=md5("123456") where user_login='帐号';

  2. swift tableViewController

    tableViewController 控制器 import UIKit     class ViewController: UITableViewController {              ...

  3. php和jsCOOKIE实现前端交互

    w如何精简? <script> document.cookie = 'wjs_cookie=' + 'amz_reviews'; function w(id) { document.coo ...

  4. FW:主流RPC框架

    主流RPC框架  2015年10月27日  zman  RPC 介绍目前在互联网公司比较流行的开源的RPC框架. RPC框架比较   语言 协议 ​服务治理 ​社区 机构 Hessian 多语言 he ...

  5. sVIrt概述

    sVirt概述 前面已经对seLInux的基本原理做了分析,seLinux主要就是基于主体和客体的安全上下文,进行访问决策.那么安全上下文是不是又可以理解为一个标签呢? 基于以上seLInux的特性, ...

  6. HttpRunner 参数化数据驱动

    HttpRunner 2.0 参数化数据驱动案例,废话不说,直接上干货. 1.测试用例目录结构      api:接口集 testcases:测试用例    testsuites:测试套件 data: ...

  7. Hadoop 入门教程

    Hadoop 入门教程 https://blog.csdn.net/kkkloveyou/article/details/52348883

  8. 003-shell 传递参数

    一.概述 可以在执行 Shell 脚本时,向脚本传递参数,脚本内获取参数的格式为:$n.n 代表一个数字,1 为执行脚本的第一个参数,2 为执行脚本的第二个参数,以此类推…… 二.实例 以下实例我们向 ...

  9. PAT 1148 Werewolf - Simple Version [难理解]

    1148 Werewolf - Simple Version (20 分) Werewolf(狼人杀) is a game in which the players are partitioned i ...

  10. Java中二叉树存储结构实现

    一.二叉树 二叉树指的是每个节点最多只能有两个子树的有序树.通常左边的子树被称为“左子树”(left subtree),右边的子树被称为右子树. 二叉树的每个节点最多只有2棵子树,二叉树的子树次序不能 ...