springmvc+mybatis下批量插入和批量更新

// 查询出没有的需要插入的
// 1:将查询出的list转为map
Map imCategoryMap = imCategoryBeanList.stream().collect(Collectors.toMap(ImCategoryBean::getfCategoryId, imCategoryBean -> imCategoryBean, (k1, k2) -> k1));
// 2: 查询出传入有的和没有的
// 2.1: 有的list需要更新
List updateImCateList = new ArrayList<>();
// 2.2: 没有的list
List insertImCateList = new ArrayList<>();
categorys.stream().forEach(cate -> {
    //能够获取到说明有
    ImCategoryBean categoryBean = imCategoryMap.get(cate.getfCategoryId());
    if (null != categoryBean) {
        // 获取当前状态是否一致,不一致更新,一致则不更新
        if (!(cate.getfCategoryType().equals(categoryBean.getfCategoryType())) || categoryBean.getfIsDelete().equals(ImConstant.DB_DELETE)) {
            ImCategoryBean imCategoryBean = new ImCategoryBean();
            imCategoryBean.setfId(categoryBean.getfId());
            imCategoryBean.setfIsDelete(ImConstant.DB_CORRECT);
            imCategoryBean.setfCategoryType(cate.getfCategoryType());
            updateImCateList.add(imCategoryBean);
        }
    } else {
        // 插入的话缺当前人
        cate.setfSysUserId(fSysUserId);
        insertImCateList.add(cate);
    }
});
//将传入的数据转换为map
Map categorysMap = categorys.stream().collect(Collectors.toMap(ImCategoryBean::getfCategoryId, imCategoryBean -> imCategoryBean, (k1, k2) -> k1));
imCategoryBeanList.stream().forEach(cate -> {
    ImCategoryBean categoryBean = categorysMap.get(cate.getfCategoryId());
    if (null == categoryBean) {//如果没有,说明已经被移除  被移除但是数据库之中还是有数据的,则需要进行逻辑删除
        ImCategoryBean imCategoryBean = new ImCategoryBean();
        imCategoryBean.setfId(cate.getfId());
        imCategoryBean.setfIsDelete(ImConstant.DB_DELETE);
        updateImCateList.add(imCategoryBean);
    }
});
//全部完成之后进行批量插入和批量更新
if (updateImCateList.size() > 0) {
    imCategoryService.batchUpdateList(updateImCateList);
}
if (insertImCateList.size() > 0) {
    imCategoryService.batchInsertList(insertImCateList);
}

在mybatis中

批量插入:


  insert into zm_im_category (f_sys_user_id, f_category_id, f_category_type)
  values
  
    (
    #{cate.fSysUserId,jdbcType=BIGINT},
    #{cate.fCategoryId,jdbcType=BIGINT},
    #{cate.fCategoryType,jdbcType=VARCHAR})
  

批量更新


  update zm_im_category
  
    
      
        when zm_im_category.f_id = (#{item.fId})
        then (#{item.fIsDelete})
      
    
      
          
              when zm_im_category.f_id = (#{item.fId})
              then (#{item.fCategoryType})
          
      
  
  where
  
    (zm_im_category.f_id = (#{item.fId}))
  

你可能感兴趣的:(springmvc,mysql)