- if test;
select * from user where <if test="id!=null and ''!=id"> id = #{id} </if> <!-- OGNL會自動進行字符串與數字間的轉換 --> <if test="des == 0 or des == 1"> and des = #{des} </if>
缺點:當id字段爲空時,sql條件語句中會出現多餘的“and”,導致錯誤。
解決方法:①條件語句開頭添加“1=1”。②mybatis用<where></where>標籤江第一個多出來的and/or去除。 -
trim標籤:自定義截取字符串;
select * from user <!-- 彌補where標籤無法去除後面多出and/or的缺點。 prefix="":前綴:爲字符串加一個前綴。 prefixOverrides="":前綴覆蓋:去掉字符串前多餘的字符。 suffix="":後綴:爲字符串加一個後綴。 suffixOverrides="":後綴覆蓋:去掉字符串後多餘的字符。 --> <trim prefix="where" suffixOverrides="and"> <if test="id !=null and ''!=id"> id = #{id} and </if> <if test="des == 0 or des == 1"> des = #{des} </if> </trim>
- choose(when,otherwise):按順序取條件查詢,只會進入其中一個條件。
select * from user <where> <!-- 順序至上而下,從第一個滿足的條件進入 --> <choose> <when test="id != null and '' != id"> id = #{id} </when> <when test="name != null and '' != name"> name like #{name} </when> <otherwise> 1=1 </otherwise> </choose> <where>
- trim中的set標籤(where,set)
update user <!-- set標籤可以將字段後面的逗號去掉 --> <set> <if test="id!=null and ''!=id"> id = #{id}, </if> <if test="des!=null and ''!=des"> des = #{des}, </if> </set> where name = #{name}
上述代碼也可用trim標籤代替。
- foreach:遍歷元素。對一個集合進行遍歷,通常在in條件語句中使用。
select * from user where id in <!-- collection:指定要遍歷的集合 item:將當前遍歷出的元素賦值給指定的變量 separator:每個元素之間的分隔符 open:在結果前拼接一個開始的字符串 close:在結果後拼接一個結束的字符串 --> <foreach collection="ids" open="(" close=")" separator="," item="id"> #{id} </foreach>
foreach還可以用於批量保存數據
INSERT INTO user(name,age,email)VALUES <foreach collection="userList" item="user" separator=","> (#{user.name},#{user.age},#{user.eamil}) </foreach>
以上爲個人學習筆記,讀者沒看明白的話可按着鏈接查看這位前輩的博文:
https://www.cnblogs.com/lc-java/p/7491693.html