存储过程在程序开发中经常用到。存储过程具有安全,高效,运行速度快等特点,在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";
}