Mybatis捕獲異常


DataAccessException

DataAccessException是Mybatis封裝的異常,繼承了RuntimeException這個類。
image

步驟

  1. Mapper接口拋出DataAccessException異常
    int insertSelective(BusArea record) throws DataAccessException;
  1. ServiceImpl拋出DataAccessException異常
    @Override
    public boolean insertSelective(BusArea busArea)  throws DataAccessException {
        boolean result = this.busAreaMapper.insertSelective(busArea) > 0;
        return result;
    }
  1. Controller捕獲異常,在捕獲DataAccessException之前可以捕獲其他runtime異常。
    @RequestMapping("insertSelective")
    @ResponseBody
    public Map insertSelective(BusArea area) {
        String uuid = UUIDGenerator.getUUID();
        area.setId(uuid);

        Map resultmap = new HashMap();
        String code = "fail";
        String msg = "添加失敗!";

        try {
            boolean rb = this.busAreaService.insertSelective(area);
            if (rb){
                code = "success";
                msg = "添加成功!";
            }
        }catch (DuplicateKeyException e){
            msg = "該區域名稱已存在,請勿重復添加!";
        }catch (DataAccessException e){
            msg = "添加出現異常!";
        }
        resultmap.put("code",code);
        resultmap.put("msg",msg);
        return resultmap;
    }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM