一.Mybatis 極簡入門
二.Mybatis 級聯查詢
三.Mybatis 延遲加載
四.Mybatis 緩存策略
本篇:Mybatis 動態SQL
首先來了解一下動態SQL的優點,它可以幫助碼農們減少不必要的重複代碼,降低工作量。
1. if 標籤
if標籤用來判斷條件是否成立,如果條件成立就執行裏面的內容,舉個例子:
<select id="findStudentByAll" parameterType="com.ibuyi.mybatis.entity.Student" resultType="com.ibuyi.mybatis.entity.Student">
select * from student
<if test="id!=0">
<!--如果id!=0,則會添加id=#{id}這個條件-->
id=#{id}
</if>
<!--如果name!=null,則會添加name=#{name}這個條件-->
<if test="name!=null">
and name=#{name}
</if>
</select>
2. where標籤
結合if標籤使用,能夠自動刪除and
<select id="findStudentByAll" parameterType="com.ibuyi.mybatis.entity.Student" resultType="com.ibuyi.mybatis.entity.Student">
select * from student
<where>
<if test="id!=0">
id=#{id}
</if>
<if test="name!=null">
and name=#{name}
</if>
</where>
</select>
看上面的代碼,如果id沒有設置,那麼語句會變成 select * from where and name=#{name}
但是我們有where標籤就能夠將這個 and刪除
3. choose標籤
<select id="findStudentByAll" parameterType="com.ibuyi.mybatis.entity.Student" resultType="com.ibuyi.mybatis.entity.Student">
select * from student
<where>
<choose>
<!--如果一個條件成立,立馬結束,多個選擇一個-->
<when test="id!=0">
and id=#{id}
</when>
<when test="name!=null">
and name=#{name}
</when>
</choose>
</where>
</select>
4. trim標籤
<select id="findStudentByAll" parameterType="com.ibuyi.mybatis.entity.Student" resultType="com.ibuyi.mybatis.entity.Student">
select * from student
<trim prefix="where" prefixOverrides="and">
<if test="id!=0">
and id=#{id}
</if>
<if test="name!=null">
and name=#{name}
</if>
</trim>
</select>
prefix和prefixOverrides不能在一起,如果在一起就把後面的刪除掉。
5.Set標籤
當我們想更新某個多字段表時,只有一個字段改動,其他字段無需要更改,但是這個字段並不確定,傳統的sql做法就是寫很多update語句,但是set標籤給我們提供了更方便的方法。
<update id="findStudentByAll">
update student
<!--只有不爲空,纔會執行set操作,也不需要重複寫多條sql語句了-->
<set>
<if test="id!=0">
id=#{id}
</if>
<if test="name!=null">
name=#{name}
</if>
</set>
where id=#{id}
</update>