Mybatis 總結

Gyoung發表於2016-05-29

1.如何傳遞多個引數

 mybatis中,如果介面有多個引數,那麼在mapper.xml中,可以通過#{0,jdbcType=VARCHAR},#{1,jdbcType=VARCHAR}或#{param1,jdbcType=VARCHAR},#{param2,jdbcType=VARCHAR}來獲取。

2.加強版的分支、選擇判斷

<select id="findActiveBlogLike"
 resultType="Blog">
 SELECT * FROM BLOG WHERE state = ‘ACTIVE’
 <choose>
 <when test="title != null">
 AND title like #{title}
 </when>
 <when test="author != null and author.name != null">
 AND author_name like #{author.name}
 </when>
 <otherwise>
 AND featured = 1
 </otherwise>
 </choose>
</select>

3.避免Where 空條件的尷尬

<select id="findActiveBlogLike" resultType="Blog">
 SELECT * FROM BLOG
 <where>
     <if test="state != null">
         and state = #{state}
     </if>
 </where> 
</select>

4.$與#的區別

1  select * from T_PRINT_LAYOUT where  D_RECID = ${recId}

最後生成的SQL為:

1 select * from T_PRINT_LAYOUT where  D_RECID = 1

即:直接將引數值替換到了原來${recId}的位置,相當於硬拼SQL

1  select * from T_PRINT_LAYOUT where  D_RECID = #{recid,jdbcType=DECIMAL}

最後生成的SQL為:

1 select * from T_PRINT_LAYOUT where  D_RECID = ?

即:#{...}被識別為一個SQL引數

 

參考:mybatis 使用經驗小結

相關文章