一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

Mybatis批量提交实现代码解析

时间:2020-12-08 编辑:袖梨 来源:一聚教程网

本篇文章小编给大家分享一下Mybatis批量提交实现代码解析,文章代码介绍的很详细,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看。

一、mapper 使用foreach 遍历

批量insert:


   INSERT INTO emp(ename,gender,email,did)
   VALUES
   
   (#{emp.eName},#{emp.gender},#{emp.email},#{emp.dept.id})
   
 

批量update:



UPDATE green_beans

stock=#{bean.stock}


beanUid = #{bean.beanUid}


二、使用 mybatis ExecutorType.BATCH

使用步骤:

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


    
      
       
     

(2)在service实现中添加:

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

demo:

@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:

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

mapper.xml :


  
    insert into employee(lastName,email,gender)
    values(#{lastName},#{email},#{gender})
  

三、总结:

方式一、需要修改数据库属性添加allowMutiQueries=true,例如:jdbc.url=jdbc:mysql://localhost:3306/mybatis?allowMultiQueries=true

方式二、需要开启事务提交,在applcationContext.xml中添加BATCH

热门栏目