当前位置: 移动技术网 > IT编程>数据库>Mysql > MyBatis的动态sql小练习,小回顾

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

2018年11月03日  | 移动技术网IT编程  | 我要评论

关键字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 ( ? , ? ) 

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网