MyBatis參數傳遞

MyBaties參數傳遞方式:
1. 單個參數
(1) 實體類屬性名傳入,如下所示:

<select id="selectUrlByConfigId" resultMap="BaseResultMap">
        select
        <include refid="Base_Column_List" />
        from spider_url_queue
        where config_id = #{config_id,jdbcType=VARCHAR}
        and state = '0'
    </select>

(2)佔位符傳入,如下所示:

<select id="selectUrlByConfigId" resultMap="BaseResultMap">
        select
        <include refid="Base_Column_List" />
        from spider_url_queue
        <!-- 此處是0就表示取第1個參數 -->
        where config_id = #{0}
        and state = '0'
    </select>

2.多個參數傳入
(1)使用實體類屬性名傳入,如下所示:

<!-- 分頁查詢 -->
<select id="getSpiderListByPage" resultMap="BaseResultMap">
    SELECT
    <include refid="Base_Column_List" />
    FROM spider_config
    ORDER BY
        id ASC
    LIMIT #{start}, #{end}
    </select>

(2)佔位符傳入,如下所示:

<!-- 分頁查詢 -->
<select id="getSpiderListByPage" resultMap="BaseResultMap">
    SELECT
    <include refid="Base_Column_List" />
    FROM spider_config
    ORDER BY
        id ASC
    LIMIT #{0}, #{1}
    </select>

(3)傳入map參數,如下所示:

參數map爲:
Map<String,Object> map = new Map<String,Object>();  
map.put("userId",userId);  
map.put("userName",userName);

dao接口:
UserManage selectByUserIdAndUserName(Map<String,Object> map); 

mapper:
<select id="selectByUserIdAndUserName" resultMap="BaseResultMap" parameterType="java.lang.String" >  
    select  *  
    from USER_MANAGE
    <!-- 注意此處是$符號,不是#號-->
    where USER_ID = ${userId} and USER_NAME = ${userName}  
</select> 

(4)list參數傳入,如下所示:

dao爲:
void updateUrlState(@Param("UrlList")List<SpiderURLQueue> spiderUrlQueueList, @Param("state")String state);

mapper:
<update id="updateUrlState">
    update spider_url_queue
    set state = #{state,jdbcType=VARCHAR}
    where id in
    <!-- foreach進行list集合遍歷
        collection:是傳入的集合參數名稱
        item:集合中每一個元素進行迭代時的別名
        index:用於表示在迭代過程中,每次迭代到的位置
        open:該語句以什麼開始
        close:以什麼結束
        separator:在每次進行迭代之間以什麼符號作爲分隔符
        -->
    <foreach collection="UrlList" item="SpiderUrl" index="index"  
         open="(" close=")" separator=",">
         #{SpiderUrl.id, jdbcType=VARCHAR}
    </foreach>
</update>

3.參考文章
[1]https://blog.csdn.net/s592652578/article/details/52871884
[2]https://blog.csdn.net/aya19880214/article/details/41961235
[3]https://blog.csdn.net/s592652578/article/details/52871660

發佈了42 篇原創文章 · 獲贊 17 · 訪問量 18萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章