MyBatis - 單參數的傳遞方式

    本章只對 Dao 接口聲明中,入參爲單個參數 且 類型爲基礎類型(Integer、Long、String 等)做說明,對於複雜類型( Bean、Map 等)和多參數類型 統一到多參數章節說明

    在 Mapper 的 XML 文件中,入參聲明的 parameterType 屬性,是可選的參數,可以不指定

    內置參數 _parameter 代表的是 Dao 接口中聲明的所有參數,當 Dao 的聲明爲單個參數時,此內置參數代表的 即當前參數

一、標準的

        使用內置參數 _parameter 獲取當前的基礎類型參數

  •     1、僅參數取值
<select id="findByUserId" resultType="com.xl.entity.Detail">
    SELECT * FROM detail WHERE user_id = #{_parameter}
</select>
  •     2、取值加判斷
<select id="findByUserId" resultType="com.xl.entity.Detail">
    SELECT * FROM detail WHERE 
    <if test="_parameter != null"> user_id = #{_parameter} </if>
</select>

二、隨意的

        單個參數 且 爲基礎類型時,在取值時,可以使用隨意的字符;但是,進行條件判斷時,必須使用 _parameter 判斷

  •     1、僅參數取值
<select id="findByUserId" resultType="com.xl.entity.Detail">
    SELECT * FROM detail WHERE user_id = #{abc}
</select>
  •     2、取值加判斷
<select id="findByUserId" resultType="com.xl.entity.Detail">
    SELECT * FROM detail WHERE 
    <!-- 判斷時非 _parameter 則異常:There is no getter for property named 'userId' in 'class java.lang.String' -->
    <if test="_parameter != null"> user_id = #{abc} </if>
</select>

三、註解的

        在 Dao 中,通過 @Param 對參數進行命名,此時 XML 中 無論 僅取值 還是 加判斷,都必須使用此命名後的名稱

List<Detail> findByUserId(@Param("userId") String userId);
<select id="findByUserId" resultType="com.xl.entity.Detail">
    SELECT * FROM detail WHERE 
    <if test="userId != null"> user_id = #{userId} </if>
</select>

 

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