动态SQL
随着用户的输入或外部条件的变化而变化的SQL语句,我们称为动态SQL
<if>
用于判断条件是否成立。使用test属性进行条件判断,如果条件为true,则拼接SQL
select *
from emp
where
<if test="name != null">
name like concat('%', #{name}, '%')
</if>
<if test="gender != null">
and gender = #{gender}
</if>
<if test="begin != null and end!=null">
and entrydate between #{begin} and #{end}
</if>
order by update_time desc
@Test
public void testList(){
// List<Emp> empList= empMapper.list("张",(short)1,LocalDate.of(2010,1,1),LocalDate.of(2020,1,1));
List<Emp> empList= empMapper.list("张",(short)1,null,null);
System.out.println(empList);
}
我们再来测试一下,会发现报错
这是因为此时name = null,name那部分SQL语句就没有执行
此时就需要用到<where>这个标签了
<where>
where标签有两个作用
第一个作用:它会根据里面的子标签动态的来判断里面的条件,如果里面所有的条件它都不成立,它就不会生成where这个关键字,如果里面有一个条件成立,它就会生成where这个关键字
第二个作用:会自动的去处掉条件前面多余的and或者是or
<set>
set和where差不多的作用,set可以把逗号删除掉
<update id="update2">
update emp
<set>
<if test="username != null">username =#{username},</if>
<if test="name != null">name=#{name},</if>
<if test="gender != null">gender=#{gender},</if>
<if test="image != null"> image=#{image},</if>
<if test="job != null"> job=#{job},</if>
<if test="entrydate != null"> entrydate=#{entrydate},</if>
<if test="deptId != null"> dept_id=#{deptId},</if>
<if test="updateTime"> update_time=#{updateTime}</if>
</set>
where id = #{id}
</update>
<foreach>
<!--批量删除-->
<!--
collection:遍历的集合
item:遍历出来的元素
separator:分隔符
open:遍历开始前拼接的SQL片段
close:遍历结束后拼接的SQL片段
-->
<delete id="deleteByIds">
delete from emp where id in
<foreach collection="ids" item="id" separator="," open="(" close=")">
#{id}
</foreach>
</delete>
<sql><include>
<sql>:定义可重用的片段
<include>:通过属性refid,指定包含的sql片段
抽取
引用