1.首先来看一下常用的属性作用
1.以下是trim标签中涉及到的属性
属性 | |
---|---|
prefix | 拼接sql语句中所用到的前缀 |
suffix | 拼接sql语句中所用到的后缀 |
prefixOverrides | 去除sql语句前面的关键字或者字符,该关键字或者字符由prefixOverrides属性指定,假设该属性指定为"AND",当sql语句的开头为"AND",trim标签将会去除该"AND" |
suffixOverrides | 去除sql语句后面的关键字或者字符,该关键字或者字符由suffixOverrides属性指定 |
2.trim的用法
mybatis的trim功能很强大,可用于给sql语句前面去拼接WHERE,SET,等前缀,或者添加’(’,’)'大小括号等后缀。也可以用于去除sql中的多余and,or关键字等。
例1:
去除多余的前缀and
select*from<trim prefix="WHERE"><if test="id!= null">
id= #{id}</if><if test="name!= null and name != null">AND name like #{name}</if>
1.这段代码,state!=null,情况下
select * from where id = #{id} and name like = #{name}
2.当id为null的异常情况下
select * from where and name like = #{name}
这个时候拼接的sql有问题,where and 肯定会报错。当加上属性 prefixOverrides=“AND”,一切回归正常。
select*from<trim prefix="WHERE" prefixOverrides="AND"><if test="id!= null">
id= #{id}</if><if test="name!= null and name != null">AND name like #{name}</if>
例2:
去除多余的后缀 ’,‘。例3:来看一个经典的trim用法
updateMCC_OFFER_FULFILL<trim prefix="set" suffixOverrides=","><trim prefix="c_name =case" suffix="end,"><foreach collection="list" item="cus"><if test="cus.name!=null">
when id=#{cus.id} then #{cus.name}</if></foreach></trim></trim>
结果:
update MCC_OFFER_FULFILL
set
c_name =
case
when id=#{cus.id} then #{cus.name}
end
2.foreach的用法
1.以下是foreach标签中涉及到的属性
item | 集合中元素迭代时的别名 |
index | 集合中元素迭代时的索引 |
open | 常用语where语句中,表示以什么开始,比如以’('开始 |
separator | 表示在每次进行迭代时的分隔符, |
close | 常用语where语句中,表示以什么结束, |
不管是多参数还是单参数的list,array类型,都可以封装为map进行传递。如果传递的
是一个List,则mybatis会封装为一个list为key,list值为object的map,如果是array,
则封装成一个array为key,array的值为object的map,如果自己封装呢,则colloection
里放的是自己封装的map里的key值
例子:常见用法:
select*FROMUSER
where idin<foreach collection="userids" item="userid" index="index" open="("
separator="," close=")">
#{userid}</foreach>
下班了! 以后再补!