美文网首页
mybatis中使用mysql存储过程注意事项

mybatis中使用mysql存储过程注意事项

作者: 大胡子的机器人 | 来源:发表于2018-11-20 13:25 被阅读0次
  • 1、navicat创建开发存储过程注意事项:
register.png
  • 2、springboot + mybatis中调用存储过程(多个in参数,多个out参数的情况)使用教程

开发架构:springboot + mybatis
第一步:基于navicat创建存储过程,代码如下(用户注册示例,注意代码业务逻辑并不完整,仅供测试教程用,上图为截图):

BEGIN
declare cnt int DEFAULT 0;
select count(1) into cnt from bv_user where mobile = p_mobile;
if cnt > 0 then 
    set o_code := -1;
    set o_message := '已注册';
ELSE
    insert into bv_user (mobile,name,avatar,create_time)values(p_mobile,p_name,p_avatar,now());
    -- MySQL 更新或插入后获取受影响行数
    SELECT ROW_COUNT() into cnt;
    -- mysql 插入一条记录后获取插入记录的主键id
    -- SELECT LAST_INSERT_ID();
    if cnt > 0 then 
        set o_code := 0;
        set o_message := 'success';
    ELSE
        set o_code := -1;
        set o_message := 'error';
    END IF;
    END IF;
END

参数为:

IN `p_mobile` varchar(20),IN `p_name` varchar(50),IN `p_avatar` varchar(255),IN `p_code` varchar(10),OUT `o_code` int,OUT `o_message` varchar(100)

第二步,配置UserMapper.xml脚本(对应数据库表user的mapper)

 <insert id="registerApp" parameterType="java.util.HashMap" statementType="CALLABLE">
{call registerApp(#{p_mobile,mode=IN,jdbcType=VARCHAR},#{p_name,mode=IN,jdbcType=VARCHAR},#{p_avatar,mode=IN,jdbcType=VARCHAR},
#{p_code,mode=IN,jdbcType=VARCHAR},#{o_code,mode=OUT,jdbcType=INTEGER},#{o_message,mode=OUT,jdbcType=VARCHAR})}
  </insert>

注意:statementType="CALLABLE" 代表的是存储过程,参数顺序需要与第一步中的参数顺序一致,否则会错乱。

第三步,service中调用:

@Service
public class UserServiceImpl implements UserService {

@Autowired
UserMapper userMapper;
@Override
public JsonResult registerApp(String mobile, String name, String avatar, String code) {

    //先查询该手机号是否注册,若注册,则提示已注册,注册失败
    try {
        Map<String,String> params = new HashMap<>();
        params.put("p_mobile",mobile);
        params.put("p_name",name);
        params.put("p_avatar",avatar);
        params.put("p_code",code);
        params.put("o_code","-1");
        params.put("o_message","");
        userMapper.registerApp(params);
        System.out.println(params.toString() + ";o_message="+params.get("o_message"));
        int ret = Integer.parseInt(String.valueOf(params.get("o_code")));
        String message = params.get("o_message");
        if(ret == 0){
            return new JsonResult(0,message);
        }else{
            return new JsonResult(ret,message);
        }
    } catch (NumberFormatException e) {
        e.printStackTrace();
        return new JsonResult(-1,e.getMessage());
    }
}
}

controller层调用代码:

@PostMapping("/register")
public JsonResult registerUser(@RequestParam("mobile") String mobile, @RequestParam("name") String name,
                               @RequestParam("avatar") String avatar,@RequestParam("code") String code){
    return userService.registerApp(mobile,name,avatar,code);
}

第四步,postman中使用post方式传参测试;


image.png

控制台查看日志输出


image.png

相关文章

网友评论

      本文标题:mybatis中使用mysql存储过程注意事项

      本文链接:https://www.haomeiwen.com/subject/cbutqqtx.html