动态SQL
- 应用场景:有时候对数据库的操作条件并不确定,例如在进行条件查询时,条件的个数我们不能预先确定,需要根据实际情况,动态调整
- 动态SQL配置主要元素有:if、where、trim、foreach、choose等
where+if标签
<select id="listEmp" parameterType="Emp" resultType="Emp">
select * from emp
<where>
<if test="empno!=null and empno!=''">
and empno = #{empno}
</if>
<if test="sal !=null and sal!=''">
and sal =#{sal}
</if>
</where>
order by empno
</select>
总结:
if+where:
1、自动添加where
2、每一个if条件前都有and,不需要考虑where后面出现and,mybatis自动处理。
3、不需要考虑空格,mybatis自动处理。
4、没有else标签,当然也没有else if标签。
5、if中判断,test="empno!=null and empno!=‘’,只可以判断属性值是否为空,不能判断属性值是否等于某个值,empno!=7788错误。
choose+when标签
<select id="listEmp" parameterType="Emp" resultType="Emp">
select * from emp
<where>
<choose>
<when test="empno!=null and empno!=''">
and empno = #{empno}
</when>
<when test="sal !=null and sal!=''">
and sal =#{sal}
</when>
<otherwise>
</otherwise>
</choose>
</where>
order by empno
</select>
总结:
choose标签:
1、多个when标签,只能执行一个。当一个when条件满足并执行后,其它的when将不在执行。
2、如果所有when标签不满足,就执行otherwise。
trim标签
- prefix属性可添加前缀,suffix属性可添加后缀。prefixOverrides属性可以去掉指定的前缀,sufixOverrides可以去掉指定的后缀
<update id="updateEmp" parameterType="Emp">
update emp
<trim prefix="set" suffix="where empno=#{empno}" suffixOverrides=",">
<if test="ename!=null and ename !=''">ename = #{ename},</if>
<if test="job!=null and job !=''">job = #{job},</if>
<if test="sal!=null and sal !=''">sal = #{sal},</if>
<if test="comm!=null and comm !=''">comm = #{comm},</if>
<if test="deptno!=null and deptno !=''">deptno = #{deptno},</if>
</trim>
</update>
总结:
trim:
1、prefix、sufix可以在SQL语句拼接出一对小括号。
2、sufixOverrides将包含内容最后一个逗号去掉。(可用于去除多余后缀)
set标签
<update id="updateEmp" parameterType="Emp">
update emp
<set>
<if test="ename!=null and ename !=''">ename = #{ename},</if>
<if test="job!=null and job !=''">job = #{job},</if>
<if test="sal!=null and sal !=''">sal = #{sal},</if>
<if test="comm!=null and comm !=''">comm = #{comm},</if>
<if test="deptno!=null and deptno !=''">deptno = #{deptno},</if>
</set>
where empno=#{empno}
</update>
总结:
set标签:
1、set标签可以在SL语句中自动加上set关键词
2、set标签自动去掉 内容后面 ,逗号
3、上面写法,必须保证最少有一个if成立。
foreach标签
- 该标签主要用于循环迭代一个集合或数组,主要用于in
<!-- 批量删除
delete from emp where empno in (7778,7900,8080)
-->
<delete id="deleteEmpByArray" parameterType="int"> <!-- 传入的参数类型为 int[] 数组类型 -->
delete from emp where empno in
<foreach collection="array" item="empno" open="(" close=")"separator=",">
#{empno}
</foreach>
</delete>
总结:
foreach:
1、collection 需要遍历类型: array、list
2、item 表示需要遍历出来对象的对象名
3、open 表示语句的开始部分
4、close 表示语句的结束部分
5、separator 表示每次迭代之间以上面符号进行分隔
6、index 每次迭代索引