动态sql语句(以我的user表为例)
1.1< sql >
对常用sql语句片段的封装
比如常用的select * from 表明
<sql id="select">
select *from user
</sql>
1.2< if >
当某条件满足时使用里面的sql片段
<if test="name!=null and name!=''">
name=#{name}
</if>
<if test="password!=null">
password=#{password}
</if>
1.3 < where >
< where > 标签代替了sql中的where
where标签只能去除第一个条件中出现的前置 and|or 关键字。
<where>
<if test="id!=0">
and id=#{id}
</if>
<if test="name!=null">
and name=#{name}
</if>
<if test="password!=null">
and password=#{password}
</if>
</where>
1.4< set >
进行修改数据时代替了原来sql语句中的 set 关键字
它的主要功能和 where 标签元素其实是差不多的,主要是在包含的语句前输出一个 set,然后如果包含的语句是以逗号结束的话将会把该逗号忽略,如果 set 包含的内容为空的话则会出错。有了 set 元素就可以动态的更新那些修改了的字段。 password多一个逗号依然可以正常运行,就是set进行的处理
<set>
<if test="name">
name=#{name},
</if>
<if test="password">
password=#{password},
</if>
</set>
1.5 < trim >对最后一个或者第一个符号的省略,和set,where类似
trim标签
prefix:前缀
prefixoverride:去掉第一个and或者是or
suffixoverride:去掉最后一个逗号(也可以是其他的标记,就像是上面前缀中的and一样)
suffix:后缀
<trim prefix="SET" suffixOverrides=",">
<if test="name" >
name =#{name},
</if>
<if test="password">
password =#{password},
</if>
</trim>
1.6 < foreach>标签
< foreach> 元素主要用在构建 in 条件中,它可以在 SQL 语句中迭代一个集合。
< foreach> 元素的属性主要有 item、index、collection、open、separator、close。
-
item 表示集合中每一个元素进行迭代时的别名。
-
index 指定一个名字,用于表示在迭代过程中每次迭代到的位置。
-
open 表示该语句以什么开始。
-
separator 表示在每次进行迭代之间以什么符号作为分隔符。
-
close 表示以什么结束。
在使用 < foreach> 元素时,最关键、最容易出错的是 collection 属性,该属性是必选的,但在不同情况下该属性的值是不一样的,主要有以下 3 种情况:
-
如果传入的是单参数且参数类型是一个 List,collection 属性值为 list。
-
如果传入的是单参数且参数类型是一个 array 数组,collection 的属性值为 array。
-
如果传入的参数是多个,需要把它们封装成一个 Map,当然单参数也可以封装成 Map。Map 的 key 是参数名,collection 属性值是传入的 List 或 array 对象在自己封装的 Map 中的 key。
<foreach collection="list" open="id in (" close=")" separator="," item="id">
#{id}
</foreach>
<foreach> 元素的属性主要有 item、index、collection、open、separator、close。