Mybatis使用注解的方式執行存儲過程並獲取返回值


開始

通過搜索引擎搜索了獲取返回值的Mybatis注解配置方式,但是都搜索不到,都是xml配置方式,嘗試自己寫出來了。

過程

  1. 首先要有一個存儲過程,in,out值。
  2. 配置mapper:
    部分代碼:
        //mybatis 注解 調用存儲過程
        @Select({
                "call execute_seckill(", "#{map.seckillId,mode=IN,jdbcType=BIGINT},", "#{map.userPhone,mode=IN,jdbcType=BIGINT},", "#{map.killTime,mode=IN,jdbcType=TIMESTAMP},", "#{map.result,mode=OUT,jdbcType=INTEGER});" }) @Results({ @Result(column="result", property="result", jdbcType= JdbcType.INTEGER) }) @Options(statementType = StatementType.CALLABLE) void killByProcedure(@Param("map") Map map);

    StatementType.CALLABLE 表示 存儲過程

    1. 配置service
      部分代碼:
            Map<String, Object> map = new HashMap<>();
            map.put("seckillId", seckillId); map.put("userPhone", userPhone); map.put("killTime", killTime); map.put("result", null); try { seckillCustomMapper.killByProcedure(map); // 獲取result System.out.println(map.get("result")); } catch (Exception e) { logger.error(e.getMessage(), e); }

    通過map相對應的可以獲取到result值。

 

@select 添加判斷

添加兩個 使用例子, 供參考:
@Select({"<script>",
"select",
" seatName,SUM(profit) as profit",
"from td_seat_single_code_profit",
"where code = #{queryType,jdbcType=VARCHAR} ",
"<![CDATA[ and tradeDate >= #{startDate,jdbcType=INTEGER} and tradeDate <= #{endDate,jdbcType=INTEGER} ]]>",
"GROUP BY seatName ",
"<if test='!flag'>ORDER BY profit </if> ",
"<if test='flag'>ORDER BY profit desc</if> ",
"LIMIT #{rankSize,jdbcType=INTEGER}",
"</script> "})
List<TdSeadeProfit> getSeatProfitListByParam(@Param("rankSize") int rankSize, @Param("startDate") int startDate, @Param("endDate") int endDate, @Param("queryType") String queryType, @Param("flag") boolean flag);

@Select({"<script>",
"SELECT seatName,SUM(profit) as profit FROM td_seat_code_chain_profit where ",
" type = #{queryFlag,jdbcType=INTEGER}",
" <if test='queryFlag ==1'>and tradingCode =#{queryType,jdbcType=VARCHAR} </if>",
" <if test='queryFlag ==2'>and industrialChain =#{queryType,jdbcType=VARCHAR} </if>",
"<![CDATA[ and tradeDate >= #{startDate,jdbcType=INTEGER} and tradeDate <= #{endDate,jdbcType=INTEGER} ]]>",
"GROUP BY seatName ",
"<if test='!flag'>ORDER BY profit </if> ",
"<if test='flag'>ORDER BY profit desc</if> ",
"LIMIT #{rankSize,jdbcType=INTEGER}",
"</script> "})
List<TdSeatCinProfit> getSeatProfitListByParam(@Param("rankSize") int rankSize, @Param("startDate") int startDate, @Param("endDate") int endDate, @Param("queryFlag") int queryFlag, @Param("queryType")String queryType,@Param("flag") boolean flag);

注意大於小於的轉義或者使用 <![CDATA[ ]]>包裹表達式


今天要獲得存儲過程的返回值,但不想用call方法感覺太麻煩, 

<select id="getUpdateHumanDisease" resultType="java.lang.String">
    declare @result varchar(50)
    exec updateHumanDisease #{0},#{1},#{2},@result output
    select @result
</select>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM