前言
本篇介紹MyBatis里如何使用動態(tài)SQL,了解如何去簡單使用動態(tài)標(biāo)簽;如有錯(cuò)誤,請?jiān)谠u論區(qū)指正,讓我們一起交流,共同進(jìn)步!
本文開始
MyBatis - 動態(tài) SQL
使用動態(tài)SQL的好處:根據(jù)不同的條件拼接 SQL 語句,提高了SQL的靈活性;
if標(biāo)簽
- if標(biāo)簽:判斷時(shí)使用,滿足test中的判斷,執(zhí)行if條件
格式:< if test=“xxx != null”> < /if >
-寫在.xml文件中
-test中的是類中屬性的值
trim標(biāo)簽
- trim標(biāo)簽:判斷時(shí)使用,去除后綴 與 if標(biāo)簽配合使用
格式:
屬性:prefix: 這個(gè)語句前面加前綴,例如 左括號(
suffix: 這個(gè)語句前面加后綴,例如 右括號(
suffixOverrides:去掉整個(gè)語句后綴,例如 末尾的逗號 ,
示例:
<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)簽:查詢時(shí)使用,如果有添加條件,就生成where語句;沒有就不添加條件,不會生成where語句;
-可以去掉前綴and (如下示例,在只有第二個(gè)條件時(shí),where會自動去掉and)
示例:文章來源:http://www.zghlxwxcb.cn/news/detail-634581.html
<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)簽:修改時(shí)使用;
-會自動去掉最后的后綴逗號,
<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)簽:刪除時(shí)使用,刪除多個(gè)就需要遍歷刪除,這就使用了foreach;
屬性:collection: 為傳遞過來的集合名稱;
open: 語句前綴;
close: 語句后綴;
item: 遍歷的每個(gè)對象的名稱;
separator: 每次遍歷 的 分隔符;
<delete id="delByIds">
delete from userinfo
where id in
<foreach collection="lists" open="(" close=")" item="id" separator=",">
#{id}
</foreach>
</delete>
總結(jié)
???各位讀友,本篇分享到內(nèi)容如果對你有幫助給個(gè)??贊鼓勵(lì)一下吧??!
感謝每一位一起走到這的伙伴,我們可以一起交流進(jìn)步?。。∫黄鸺佑桶桑。。?/font>文章來源地址http://www.zghlxwxcb.cn/news/detail-634581.html
到了這里,關(guān)于認(rèn)識MyBatis 之 MyBatis的動態(tài)SQL的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!