动态SQL的写入

许多时候我们的SQL语句都不是静态写好的,都需要根据各种条件动态拼接,比如如果用户输入了用户名和年龄,那么我们就通过用户名和年龄一起查询,如果只添加了用户名,那么我们只通过用户名查询,但是在mybatis中在XML中是不可以实现动态拼接的,拼接主要是使用OGNL表达式。

第一个标签 <if test =>

<select id="selByAccinAccout" resultType="log">
select * from log where 1=1
<!-- OGNL 表达式,直接写 key 或对象的属性.不需要添加任
何特字符号 -->
<if test="accin!=null and accin!=''">
and accin=#{accin}
</if>
<if test="accout!=null and accout!=''">
and accout=#{accout}
</if>
</select>

第二个标签 <where>

正如第一个标签 如果我只是单纯的使用if语句,那么我们必须在where后加一个1=1不然 where与and连一起就会错误,。

where的作用就是在前边添加一个where 并且删掉一个and 

<select id="selByAccinAccout" resultType="log">
select * from log
<where>
<if test="accin!=null and accin!=''">
and accin=#{accin}
</if>
<if test="accout!=null and accout!=''">
and accout=#{accout}
</if>
</where>
</select>

第三个标签是 <choose> <when> <otherwise> 

他相当于是switch case 他的作用就是选择一个合适的条件,然后拼接进去

<select id="selByAccinAccout" resultType="log">
select * from log
<where>
<choose>
<when test="accin!=null and accin!=''">
and accin=#{accin}
</when>
<when test="accout!=null and accout!=''">
and accout=#{accout}
</when>
</choose>
</where>
</select>

第四个标签是<set>

它主要是应用在update语句中 update 表名 set 属性 =    where   这个标签的作用就是添加一个set 并且删掉最后的逗号 

但是需要注意的是set 要求在外部添加一个id =#{id} (根据where后的条件进行添加) 不填加会导致只有set后边没句子报错

<update id="upd" parameterType="log" >
update log
<set>
id=#{id},
<if test="accIn!=null and accIn!=''">
accin=#{accIn},
</if>
<if test="accOut!=null and accOut!=''">
accout=#{accOut},
</if>
</set>
where id=#{id}
</update>

第五个标签Trim

prefix 在前面添加内容
 prefixOverrides 去掉前面内容
suffix 在后面添加内容
suffixOverrieds 去掉后面内容
执行顺序去掉内容后添加内容

<update id="upd" parameterType="log">
update log
<trim prefix="set" suffixOverrides=",">
a=a,
</trim>
where id=100
</update>

第六个标签 <bind标签 、

他主要用于给边变量重新赋值,一般用于模糊查询给参数添加%

<select id="selByLog" parameterType="log"
resultType="log">
<bind name="accin" value="'%'+accin+'%'"/>
#{money}
</select>

第七个便签 ,foreach标签

主要适用于 in 查询 。select *from id in 1,2,3 

collectino=”” 要遍历的集合
 item 迭代变量, #{迭代变量名}获取内容
 open 循环后左侧添加的内容
 close 循环后右侧添加的内容
 separator 每次循环时,元素之间的分隔符

<select id="selIn" parameterType="list"
resultType="log">
select * from log where id in
<foreach collection="list" item="abc" open="("
close=")" separator=",">
#{abc}
</foreach>
</select>

第八个标签 <sql> 和<includ

主要用于SQL部分片段的复用

定义一个片段 

<sql id="mysql">
id,accin,accout,money
</sql>

使用Include应用

<select id="">
select <include refid="mysql"></include>
from log
</select>

猜你喜欢

转载自blog.csdn.net/weixin_41298572/article/details/88626412