儲存過程在程式開發中經常用到。儲存過程具有安全,高效,執行速度快等特點,在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";
}