Mybatis调用带有IN、OUT和INOUT的存储过程

390 阅读1分钟

此文详细讲解了在mybatis里如何配置并使用postgres的存储过程,以及详细的介绍存储过程的mode=IN,mode=OUT,mode=INOUT的使用分别对应的示例及结果

准备阶段

  1. 首先我们创建一个简单的输入宽、高计算面积的一个存储过程(area_of_rectangle)
CREATE OR REPLACE FUNCTION "public"."area_of_rectangle"("wide" , "height" )
RETURNS "pg_catalog"."int4" AS $BODY$
declare
        area integer := 0;
begin
        area := wide * height;
        return area;
end
$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100
  1. mybatis的xml基础示例块如下
<select id="findArea"  parameterType="map" statementType="CALLABLE" resultType="java.util.Map">
    {call area_of_rectangle(
            #{wide, mode=IN, jdbcType=INTEGER},
            #{height, mode=IN, jdbcType=INTEGER}
        )}
</select>
  1. 使用get请求调用上述mybatis的接口如下
@GetMapping("/tool/findArea")
public ResultEntity findArea(){
    Map<String,Object> param = new HashMap<>();
    param.put("wide",10);
    param.put("height",11);
    testMapper.findArea(param);
    return ResultEntity.success(param);
}

测试调用area_of_rectangle存储过程

一、IN、OUT类型的输入输出

  1. 修改findArea xml配置,增加result参数,OUT类型的输出
<select id="findArea"  parameterType="map" statementType="CALLABLE" resultType="java.util.Map">
    {call area_of_rectangle(
            #{wide, mode=IN, jdbcType=INTEGER},
            #{height, mode=IN, jdbcType=INTEGER},
            #{result, mode=OUT, jdbcType=INTEGER}
        )}
</select>
  1. 调用/tool/findArea接口后,发现返回值的data中多了一个result,由此可见,out类型的输出为存储过程的最终结果
{
  "code": 0,
  "msg": "success",
  "status": true,
  "data": {
    "result": 110,
    "wide": 10,
    "height": 11
  }
}

二、IN、INOUT类型的输入输出

  1. 修改findArea xml配置,将height参数的mode类型由IN改为INOUT
<select id="findArea"  parameterType="map" statementType="CALLABLE" resultType="java.util.Map">
    {call area_of_rectangle(
            #{wide, mode=IN, jdbcType=INTEGER},
            #{height, mode=INOUT, jdbcType=INTEGER}
        )}
</select>
  1. 调用/tool/findArea接口后,返回值如下。原height参数入参为11, 出参变为110,由此可见当mode参数类型声明为INOUT时,该参数即是入参也是出参
{
  "code": 0,
  "msg": "success",
  "status": true,
  "data": {
    "wide": 10,
    "height": 110
  }
}