本人微信公众号"aeolian"~

数据库唯一性约束异常插入处理

数据库

CREATE TABLE `auth_role` (
    `id` INT(11) NOT NULL AUTO_INCREMENT COMMENT '主键',
    `rolename` VARCHAR(50) NULL DEFAULT NULL COMMENT '角色名称',
    `adduser` INT(11) NULL DEFAULT NULL COMMENT '添加人',
    `addtime` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '添加时间',
    PRIMARY KEY (`id`),
    UNIQUE INDEX `rolename` (`rolename`)
)COMMENT='统一平台角色'
COLLATE='utf8_general_ci'
ENGINE=InnoDB
ROW_FORMAT=COMPACT
AUTO_INCREMENT=15;

Controller

    @RequestMapping(value="/insertSelective",method={RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public Object insertSelective(Auth_role record,HttpSession session){
        Userinfo sessionUserinfo = (Userinfo)session.getAttribute("CURR_USER");
        String sessionuserid = sessionUserinfo.getUserid().toString();
        record.setAdduser(Integer.parseInt(sessionuserid));
Map map
= new HashMap(); int result = 0; /*异常处理*/ try { result = service.insertSelective(record); }catch (org.springframework.dao.DuplicateKeyException e){ /*异常处理截获流程,如果是存在DuplicateKeyException则是重名,直接返回到前端,id主键为自增长,不会重复*/ map.put("code", "fail"); map.put("msg", "该角色名已存在!"); return map; } /*正常返回流程*/ if (result == 1) { map.put("code", "success"); map.put("msg", CN_MessageEnum.AddSuccess.getName()); }else { map.put("code", "fail"); map.put("msg", CN_MessageEnum.AddFailed.getName()); } return map; }

 

点赞

Leave a Reply

Your email address will not be published. Required fields are marked *