MyBatis的动态sql小练习,小回顾

关键字if+trim

trim可以去除多余的关键字,是where和set的组合

trim标记是一个格式化的标记,可以完成set或者是where标记的功能,如下代码:

<trim prefix="" suffix="" suffixOverrides="" prefixOverrides=""></trim>
prefix:在trim标签内sql语句加上前缀。
suffix:在trim标签内sql语句加上后缀。
suffixOverrides:指定去除多余的后缀内容,如:suffixOverrides=",",去除trim标签内sql语句多余的后缀","。
prefixOverrides:指定去除多余的前缀内容
<select id="select03" resultMap="BaseResultMap">
select * from personDemo
<trim prefix="where" prefixOverrides="and|or">
//这里的trim意思是代替where,并且在某个条件下,把多余的and或者or去掉比如name为空的时候
//第二条age是不是会有个and,这样sql语句就错了,这时候prefixOverride就可以把and去掉
//prefixOverrides去掉前缀的and 关键字
<if test="name !=null and name!=''">
name=#{name}
</if>
<if test="age !=null and age!=''">
and age=#{age}
</if>
<if test="id !=null and id!=''">
and id=#{id}
</if>
</trim>
</select>

<update id="update02" parameterType="com.demo.mybatisdemo.bean.Person">
update personDemo
<trim prefix="set" suffixOverrides=",">
<if test="name != null and name != ''">
name=#{name},
</if>
<if test="age != null and age !=''">
age=#{age}
</if>
</trim>
where id=#{id}
</update>


标签<choose><when><otherwise>
这个类似于java里面的switch标签,首先在choose标签里面,加入判断条件<when>如果有一个when的条件符合,那么久不执行其他when标签,假如所有when标签都不符合,那么就执行
<otherwise>标签里面的内容
<update id="update03" parameterType="com.demo.mybatisdemo.bean.Person">

update personDemo
  <set>
<choose>
<when test="name!=null and name.length>0">
name=#{name}
</when>
<when test="age!=null and age.length>0">
age=#{age}
</when>
<otherwise>
name='BBBBB'
</otherwise>
</choose>
</set>
where id=#{id}
</update>

还有标签<foreach>,多配合 关键字in使用
这个标签就是循环,里面有collection,item,open,separator,close
collection接口,例如传入一个数组ids,那么这个值为array,如果是list,那么这个值为list
item为传入的值的名字,如传入String[] ids 那么item为ids
open,即开头拼接的字符
close,结束拼接的字符
separator,中间分割的字符


<select id="select04" resultMap="BaseResultMap">
select * from personDemo where id in

<foreach collection="array" item="ids" open="(" separator="," close=")">
#{ids}
</foreach>

</select>
上面这段SQL打印出来为:select * from personDemo where id in ( ? , ? ) 

猜你喜欢

转载自www.cnblogs.com/hickup089/p/9897242.html