1.批量添加
dao层
/** * 批量新增商品类别 * @param productCategoryList * @return 影响的行数 */ public int batchInsertProductCategory(List<ProductCategory> productCategoryList);
在编写mapper时,因为传入的是List,所以要写的parameterType=“java.util.List”
然后需要使用<foreach来进行批量插入
<!--public int batchInsertProductCategory(List<ProductCategory> productCategoryList);--> <insert id="batchInsertProductCategory" parameterType="java.util.List"> INSERT INTO product_category(product_category_name, priority, create_time, shop_id) VALUES <foreach collection="list" item="productCategory" index="index" separator=","> ( #{productCategory.productCategoryName}, #{productCategory.priority}, #{productCategory.createTime}, #{productCategory.shopId} ) </foreach> </insert>
service层
/** * 批量添加商品类别 * @param productCategoryList * @return */ public ProductCategoryExecution batchAddProductCategory(List<ProductCategory> productCategoryList);
impl
@Override @Transactional public ProductCategoryExecution batchAddProductCategory(List<ProductCategory> productCategoryList) { if(productCategoryList != null && productCategoryList.size() >= 0){ int effecNum = productCategoryDao.batchInsertProductCategory( productCategoryList ); try{ if(effecNum <= 0){ throw new ProductCategoryException( "商品类别创建失败" ); }else{ return new ProductCategoryExecution( ProductCategoryEnum.SUCCESS); } } catch (Exception e){ throw new ProductCategoryException("batchAddProductCategory Error: " + e.getMessage()); } } else{ return new ProductCategoryExecution(ProductCategoryEnum.EMPTY_LIST); } }
Controller层
@RequestMapping(value="addproductcategories", method = RequestMethod.POST) @ResponseBody public Map<String, Object> addProductCategories(@RequestBody List<ProductCategory> productCategoryList, HttpServletRequest request){ Map<String, Object> modelMap = new HashMap<>(); Shop currentShop = new Shop(); currentShop.setShopId(1L); for(ProductCategory productCategory : productCategoryList){ productCategory.setShopId( currentShop.getShopId() ); } if(productCategoryList != null && productCategoryList.size() > 0){ ProductCategoryExecution productCategoryExecution = null; try{ productCategoryExecution = productCategoryService.batchAddProductCategory( productCategoryList ); if(productCategoryExecution.getState() == ProductCategoryEnum.SUCCESS.getState()){ modelMap.put( "success", true ); }else{ modelMap.put( "success", false ); modelMap.put( "errMsg", productCategoryExecution.getStateInfo()); } }catch(ProductCategoryException e){ modelMap.put( "success", false ); modelMap.put( "errMsg", e.getMessage()); return modelMap; } }else{ modelMap.put( "success", false ); modelMap.put( "errMsg", "请至少输入一个商品类别"); } return modelMap; }