北京西站到八達嶺長城最快路線上海優(yōu)化關(guān)鍵詞的公司
前言
本篇介紹MyBatis里如何使用動態(tài)SQL,了解如何去簡單使用動態(tài)標(biāo)簽;如有錯誤,請在評論區(qū)指正,讓我們一起交流,共同進步!
文章目錄
- 前言
- MyBatis - 動態(tài) SQL
- if標(biāo)簽
- trim標(biāo)簽
- where標(biāo)簽
- update + set 標(biāo)簽
- delete + foreach 標(biāo)簽
- 總結(jié)
本文開始
MyBatis - 動態(tài) SQL
使用動態(tài)SQL的好處:根據(jù)不同的條件拼接 SQL 語句,提高了SQL的靈活性;
if標(biāo)簽
- if標(biāo)簽:判斷時使用,滿足test中的判斷,執(zhí)行if條件
格式:< if test=“xxx != null”> < /if >
-寫在.xml文件中
-test中的是類中屬性的值
trim標(biāo)簽
- trim標(biāo)簽:判斷時使用,去除后綴 與 if標(biāo)簽配合使用
格式:
屬性:prefix: 這個語句前面加前綴,例如 左括號(
suffix: 這個語句前面加后綴,例如 右括號(
suffixOverrides:去掉整個語句后綴,例如 末尾的逗號 ,
示例:
<insert id="add4">insert into userinfo<trim prefix="(" suffix=")" suffixOverrides=","><if test="username != null">username,</if><if test="password">password,</if></trim>values<trim prefix="(" suffix=")" suffixOverrides=","><if test="username != null">#{username},</if><if test="password != null">#{password},</if></trim></insert>
where標(biāo)簽
- where標(biāo)簽:查詢時使用,如果有添加條件,就生成where語句;沒有就不添加條件,不會生成where語句;
-可以去掉前綴and (如下示例,在只有第二個條件時,where會自動去掉and)
示例:
<select id="testWhere" resultType="com.example.demo.model.Userinfo">select * from userinfo <where><if test="id > 0">id=#{id}</if><if test="username != null">and username=#{username}</if></where></select>
update + set 標(biāo)簽
- update + set標(biāo)簽:修改時使用;
-會自動去掉最后的后綴逗號,
<update id="update">update userinfo<set><if test="username != null">username=#{username},</if><if test="password != null">password=#{password}</if></set>where id=#{id}</update>
delete + foreach 標(biāo)簽
- delete + foreach標(biāo)簽:刪除時使用,刪除多個就需要遍歷刪除,這就使用了foreach;
屬性:collection: 為傳遞過來的集合名稱;
open: 語句前綴;
close: 語句后綴;
item: 遍歷的每個對象的名稱;
separator: 每次遍歷 的 分隔符;
<delete id="delByIds">delete from userinfowhere id in<foreach collection="lists" open="(" close=")" item="id" separator=",">#{id}</foreach></delete>
總結(jié)
???各位讀友,本篇分享到內(nèi)容如果對你有幫助給個👍贊鼓勵一下吧!!
感謝每一位一起走到這的伙伴,我們可以一起交流進步!!!一起加油吧!!!