最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
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
相关文章
- SpringBoot自定义bean绑定解析 10-24
- Javaweb工程运行报错HTTP Status 404解决教程 10-20
- JAVA获取jvm和操作系统相关信息方法 10-20
- BeanFactory和FactoryBean的区别讲解 10-20
- 微信小程序的宿主环境实现教程 10-10
- dispatchEvent解决重叠元素响应事件教程 10-10