一、select經常使用標籤:java
where標籤,若是該標籤下返回的內容是以AND 或OR 開頭的,則它會剔除掉。數據庫
不使用where標籤:mybatis
whereapp
<if test=" id!=null and id!='' ">ide
id=12345spa
</if>.net
<if test=" name!=null and name!='' ">xml
and name="張三"對象
</if>blog
若是id爲空,則if標籤返回的就只有 and name="張三" 和前面where連起來:where and name="張三" 多了and,確定報錯。
而標籤<where>下
<where>
<if test=" id!=null and id!='' ">
id=12345
</if>
<if test=" name!=null and name!='' ">
and name="張三"
</if>
</where>
若是id爲空,則if標籤返回的是 and name="張三" 由where 標籤刪除and加上where獲得:where name="張三"
二、update經常使用標籤
set標籤和if標籤
若是某項爲null不進行更新,保持數據庫原值。
update employee
<set>
<if test=" gender!=null and gender!='' ">
gender=#{gender},
</if>
<if test=" name!=null and name!='' ">
name=#{name}
</if>
</set>
where id = #{id};
另,若是name未null ,沒有set標籤,就多了 個逗號,所以set 的功能:若是該標籤下返回的內容是以逗號結尾的,則它會剔除掉。
三、delete經常使用標籤
foreach標籤--批量刪除
collection 指定要遍歷的集合,list類型的參數會特殊處理封裝在map中,key就叫list
item 將當前遍歷出的元素賦值給指定的變量
separator 每一個元素之間的分隔符
open 在遍歷出全部的結果以後拼接一個開始的字符串
close 遍歷出全部的結果後拼接一個結束的字符
index 索引 遍歷list 的時候是索引,遍歷map的時候是map的key,item即爲當前項的值。
(原文:https://blog.csdn.net/qq_33574890/article/details/78828785 )
舉例:
delete from employee where id in
<foreach collection="array" item="id" index="index" open="(" close=")" separator=",">
#{id}
</foreach>
傳入參數 int[] ids = {1,2,3,4,5}
四、insert經常使用標籤
insert into smbms_user(
<trim suffixOverrides=",">
<if test=" gender!=null and gender!='' ">
gender,
</if>
<if test=" name!=null and name!='' ">
name
</if>
</trim>
) values(
<trim suffixOverrides=",">
<if test=" gender!=null and gender!='' ">
#{gender},
</if>
<if test=" name!=null and name!='' ">
#{name}
</if>
</trim>
)
注意:
<trim prefix="WHERE" prefixOverrides="AND|OR"> 效果等同於<where>
<trim prefix="SET" suffixOverrides=","> 效果等同於<set>
五、樹形查找
好比一個做者對象有多篇文章對象
現有Author類,Article類
一對多狀況:Author下有一個列表屬性 private List<Article> articleList;
authorMapper.xml 這裏把author的id傳過去
<resultMap id="AuthorWithArticles" type="Author">
<id column="id" property="id" jdbcType="VARCHAR" javaType="java.lang.String"/>
<result column="userName" property="userName" jdbcType="VARCHAR" javaType="java.lang.String"/>
<collection property="articleList" column="id" select="test.mybatis.dao.articleMapper.selectArticleListByAuthorId" />
</resultMap>
在articlemapper.xml有對應的select方法
<select id="selectArticleListByAuthorId" parameterType="java.lang.String" resultType="Author" >
select * from
tb_article where AuthorId=#{Id}
</select>
更多參考:https://blog.csdn.net/weixin_42608550/article/details/81084091