Mybatis批量提交实现步骤详解
简介:mybatis的批量操作减少数据库连接次数
一、mapper使用foreach遍历
批量insert:
INSERTINTOemp(ename,gender,email,did) VALUES (#{emp.eName},#{emp.gender},#{emp.email},#{emp.dept.id})
批量update:
UPDATEgreen_beans stock=#{bean.stock} beanUid=#{bean.beanUid}
二、使用mybatisExecutorType.BATCH
使用步骤:
(1)在全局配置文件applcationContext.xml中加入
(2)在service实现中添加:
@Autowired
privateSqlSessionsqlSession;
//批量保存员工
@Override
publicIntegerbatchEmp(){
//TODOAuto-generatedmethodstub
//批量保存执行前时间
longstart=System.currentTimeMillis();
EmployeeMappermapper=sqlSession.getMapper(EmployeeMapper.class);
for(inti=0;i<10000;i++){
mapper.addEmp(newEmployee(UUID.randomUUID().toString().substring(0,5),"b","1"));
}
longend=System.currentTimeMillis();
longtime2=end-start;
//批量保存执行后的时间
System.out.println("执行时长"+time2);
return(int)time2;
}
demo:
@Test//批量保存方法测试
publicvoidtestBatch()throwsIOException{
SqlSessionFactorysqlSessionFactory=getSqlSessionFactory();
//可以执行批量操作的sqlSession
SqlSessionopenSession=sqlSessionFactory.openSession(ExecutorType.BATCH);
//批量保存执行前时间
longstart=System.currentTimeMillis();
try{
EmployeeMappermapper=openSession.getMapper(EmployeeMapper.class);
for(inti=0;i<1000;i++){
mapper.addEmp(newEmployee(UUID.randomUUID().toString().substring(0,5),"b","1"));
}
openSession.commit();
longend=System.currentTimeMillis();
//批量保存执行后的时间
System.out.println("执行时长"+(end-start));
//批量预编译sql一次==》设置参数==》10000次==》执行1次677
//非批量(预编译=设置参数=执行)==》10000次1121
}finally{
openSession.close();
}
}
mapper:
publicinterfaceEmployeeMapper{
//批量保存员工
publicLongaddEmp(Employeeemployee);
}
mapper.xml:
insertintoemployee(lastName,email,gender) values(#{lastName},#{email},#{gender})
三、总结:
方式一、需要修改数据库属性添加allowMutiQueries=true,例如:jdbc.url=jdbc:mysql://localhost:3306/mybatis?allowMultiQueries=true
方式二、需要开启事务提交,在applcationContext.xml中添加BATCH
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。