if标签:
<if>用法类似Java中的if语句,选择性拼接指定SQL片段.
补充:
- 在test条件中使用动态SQL中传递参数要放在实体对象中,不然会报错找不到对象
- 如果不放在实体对象中传输,就在test对比中使用_parameter或者value
- _parameter,value代表传进来的参数,如果传进来的参数是多个,那个_parameter代表get(0)第一个
格式:
<if test="条件">
SQL片段
</if>
说明:
- 当条件为true时,将SQL片段拼接到该标签所在位置
<choose>,<when>,<otherwise>
用法类似Java的if else if 语句,用于多次判断,选择性拼接指定SQL片段.
格式:
<choose>
<when test="条件1">SQL片段1</when>
<when test="条件2">SQL片段2</when>
...
<otherwise>默认SQL片段</otherwise>
</choose>
说明:
- <choose>,<when>,<otherwise>不能单独使用,必须混合使用.
- <choose>中可以含有N个<when>,0或1个<otherwise>
<forEach>标签:
用于遍历集合,通常用于构建in语句中.
格式:
<select id="业务匿名" resultType="结果类型[类全名]" >
select 字段列 from 表名 where 字段名 in
<foreach collection="集合" item="变量A" index="变量B" open="" separator="" close="">
#{变量A}
</foreach>
</select>
说明:
- collection属性值为集合类型的属性名.
- item属性值为变量名,名称任意.该变量存放当前元素/键值
- index属性值为变量名,名称任意.该变量存放当前元素索引/键名
- open,separator,close属性值为符号,表示遍历开始/中间/结束时拼接的符号
<!--测试<forEach: 测试age为20,21,22,23,24,25-->
<select id="dynacSQL3" resultType="user" parameterType="java.util.List" >
select * from user where age in
<foreach collection="list" item="ageval" open="(" separator="," close=")">
#{ageval}
</foreach>
</select>
<!--测试<forEach: 测试age为20,21,22,23,24,25-->
<select id="dynacSQL3" resultType="user" parameterType="java.util.ArrayList" >
select * from user where age in
<foreach collection="array" item="ageval" open="(" separator="," close=")">
#{ageval}
</foreach>
</select>
where标签:
要求:
<where>需要与<if>,<choose>,<when>,<otherwise>等配合使用
作用:
a.当至少有1个子标签的条件为true时,<where>生成1个"where"关键字.
b.若where后紧挨"AND/OR"时[where and 条件],<where>自动去除.
格式:
<where>
其他动态SQL标签
</where>
说明:
1.<where>标签中编写<if>,<choose>,<when>,<otherwise>,<forEach>等标签
set标签:
<set>用于修改命令中,能够动态前置"set"关键字,同时可以删除多余的逗号.
格式:
<update id="业务匿名" resultType="int">
update 表名
<set>
其他动态SQL标签或SQL片段
</set>
</update>
说明:
- <set>标签中编写<if>,<choose>,<when>,<otherwise>等标签
<sql>在业务标签外,定义一个SQL片段,在其他业务标签中可以通过<include>引用该SQL片段.
格式:
<sql id="SQL片段匿名">
SQL片段
</sql>
说明:
- SQL片段内容可以是SQL语句的任何部分.
- <sql>标签对之间可以嵌套动态SQL标签,产生更加方便的SQL片段
- 当需要引用SQL片段时,编写<include refid="SQL片段匿名">即可引用.