您的位置:首页 > 编程语言 > Java开发

Spring Mvc那点事---(14)Spring Mvc之mybatis调用存储过程

2016-06-10 16:54 387 查看
     存储过程在程序开发中我们经常用到。存储过程具有安全,高效,运行速度快等特点,在mybatis中我们也可以调用存储过程。这一节我们看看怎么使用。接下来的例子是根据分类ID查询当前分类下所有商品的数量。

    

---创建存储过程,In表示输入参数  out表示输出参数
DELIMITER $
CREATE  PROCEDURE  GetSkuCountProc (IN categoryId INT, OUT count_num INT )
BEGIN
SELECT COUNT(0) INTO  count_num  FROM skus s INNER JOIN category  c ON s.categoryid=c.id
WHERE c.Id=categoryId;
END
$

---调用存储过程
DELIMITER ;
SET @count = 0;
CALL GetSkuCountProc(6, @count);
SELECT @count;
    配置Mapper.xml文件

    

<select id="getSkuCount" parameterMap="getSkuCountMap" statementType="CALLABLE">
CALL GetSkuCountProc(?,?)
</select>
<parameterMap type="java.util.Map" id="getSkuCountMap">
<parameter property="categoryId" mode="IN" jdbcType="INTEGER"/>
<parameter property="count_num" mode="OUT" jdbcType="INTEGER"/>
</parameterMap>
    调用存储过程

   

@RequestMapping(value="GetSkuCount")
public String GetSkuCount()
{
String resource = "/conf.xml";
//加载mybatis的配置文件
InputStream inputstream =this.getClass().getResourceAsStream(resource);

SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(inputstream);

SqlSession session = sessionFactory.openSession();

String statesql= "mapping.skusMapper.getSkuCount";//在skusMapper.xml中有命名空间+方法名

Map<String, Integer> map = new HashMap<String, Integer>();
map.put("categoryId",6);
map.put("count_num", -1);
session.selectOne(statesql, map);
Integer result = map.get("count_num");
System.out.println(result);
return "index";
}
      通过Map来进行存储过程参数传递。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息