关于【Java】批量与单个的统一

2018-09-30  本文已影响0人  吕吕吕丶

先贴一些代码。

@RestController
public class ShopCartRestController implements ShopCartService {
    private static final Logger LOGGER = LoggerFactory.getLogger(ShopCartRestController.class);
    @Autowired
    private ShopCartManager     shopCartManager;

    @Override
    @RequestMapping(value = "/batchDelete", method = { RequestMethod.POST })
    public XResponse<Boolean> batchDelete(@RequestBody CommonShopCartVO commonShopCartVO) {
        try{
            int raw = shopCartManager.batchDelete(commonShopCartVO);
            if(raw  > 1){
                return new XResponse<Boolean>(XResponse.SUCCESS,"批量删除成功",true);
            }else if(raw  == 1){
                return new XResponse<Boolean>(XResponse.SUCCESS,"删除成功",true);
            }else {
                return new XResponse<Boolean>(XResponse.ERRCODE,"删除失败",false);
            }
        } catch (BizException e) {
//            e.printStackTrace();
            LOGGER.error(e.getMessage());
            return new GanjieResponse<Boolean>(Constant.ERRCODE,e.getMessage(),false);
        }
    }
}

commonShopCartVO中gsgBizId 以 xxx,xxx,xxx/xxx 形式传过来,根据操作的长的判断是否是批量
单个的话最后得到的times等于1,多值大于1。所以可以使XResponse返回给客户端正确的提示。

    @Transactional(rollbackFor = {BizException.class, Exception.class})//->回滚注解
    public int batchDelete(CommonShopCartVO commonShopCartVO) throws BizException{
        String []codeList = commonShopCartVO.getGsgBizId().split(",");
        int times = 0;
        for(int a = 0 ; a < codeList.length ; a++){
            if(StringUtils.isNotBlank(codeList[a])){
                CommonShopCartVO param =  new CommonShopCartVO();
                param.setUserBizId(commonShopCartVO.getUserBizId());
                param.setDeleted(true);
                param.setGsgBizId(codeList[a]);
//                LOGGER.warn(JSON.toJSONString(param));
                int tiaoshu = shopCartMapper.batchDelete(param);//->删除的条数
                times += tiaoshu;
            }
        }
        return times;
    }

注:XResponse类

public class XResponse<T> implements Serializable {
    private static final long serialVersionUID = 2757354524710232976L;
    public static final String SUCCESS = "200";
    public static final String ERRCODE = "500";
    private String code;                //返回code,类似于200/500
    private String message;             //返回文字表述
    private T      data;                //返回内容:返回值
    private Object ext;                 //扩展信息

    public XResponse() {

    }
    public XResponse(String errCode, String errorMessage) {
        this.code = errCode;
        this.message = errorMessage;
    }
    //定义一个返回,做法是为了让客户端知道
    public XResponse(String code, String message, T data) {
        this.code = code;
        this.message = message;
        this.data = data;
    }
    //封装
    ···
}
上一篇下一篇

猜你喜欢

热点阅读