介绍
- collection:必填,值为要迭代循环的属性名。这个属性值的情况有很多
- item :变量名,值为从迭代对象中取出来的每一个值
- index: 索引的属性名,在集合数组情况下值为当前索引值,当迭代循环的对象时Map类型时,这个值为map的key值
- open: 整个循环内容开头的字符串
- close:整个循环内容结尾的字符串
- separator: 每次循环的分隔符
XML
<insert id="insertCustomersBatch" parameterType="java.util.List"> insert into STOREROOM_REPERTORY(UUID, CUSTOMERSNAME, CUSTOMERSNO, COMMUNITY, REPERTORY_CODE, REPERTORY_AREA, COLOUR, CREATE_DATE, LOT, STATUS, OPERATOR_DATE) <foreach collection="list" item="item" index="index" separator="union all"> ( SELECT #{item.uuid}, #{item.customersname}, #{item.customersno}, #{item.community}, #{item.repertoryCode}, #{item.repertoryArea}, #{item.colour}, #{item.createDate}, #{item.lot}, #{item.status}, #{item.operatorDate} FROM DUAL ) </foreach> </insert>
Dao 数据层
void insertCustomersBatch(@Param("list") List<StoreroomRepertory> list);
service业务层
@Transactional(readOnly = false) @Override public void insertCustomersBatch(List<StoreroomRepertory> list) { StoreroomRepertory storeroomRepertory = new StoreroomRepertory(); try { int batchCount = 50;//每批commit的个数 int batchLastIndex = batchCount - 1;//每批最后一个的下标 for(int index = 0; index < list.size()-0;){ if(batchLastIndex > list.size()-1){ batchLastIndex = list.size(); storeroomRepertoryDao.insertCustomersBatch(list.subList(index, batchLastIndex)); System.out.println("index:"+index+" batchLastIndex:"+batchLastIndex); storeroomRepertory.setOperatorDate(new Date()); break;//数据插入完成,退出循环 }else{ storeroomRepertoryDao.insertCustomersBatch(list.subList(index, batchLastIndex)); System.out.println("index:"+index+" batchLastIndex:"+batchLastIndex); index = batchLastIndex;//设置下一批下标 batchLastIndex = index + (batchCount - 1); if(index==list.size()-1){ storeroomRepertoryDao.insertCustomersBatch(list.subList(index, index+1)); } } } }catch(Exception e){ //事务回滚 TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); // 设置回滚点 Object savePoint = TransactionAspectSupport.currentTransactionStatus().createSavepoint(); // 回滚到 savePoint TransactionAspectSupport.currentTransactionStatus().rollbackToSavepoint(savePoint); log.error("批量异常捕获",e); e.printStackTrace(); } } controller控制层 @RequestMapping(value = "insertCustomersBatch",method = RequestMethod.POST) @ApiOperation(value = "批量订单入库") public PmpResult insertCustomersBatch(@RequestBody List<StoreroomRepertory> list){ try { storeroomRepertoryService.insertCustomersBatch(list); logger.info("批量入库成功"); return PmpResult.success(list); } catch (Exception e) { logger.error(e.getMessage(), e); String errorMessage = "异常的入库添加"; if (isDev) { errorMessage = e.getMessage(); } return PmpResult.paramError(errorMessage); } }