前言
还留有尾巴,这一篇主要是关于动态SQL语句的。文章初衷仅供个人学习使用,如果也对你有所帮助,小子深感荣幸。
一、简介
动态SQL语句,其实就是按照外部用户输入或者外部条件的变化而发生变化。举个例子以方便理解:
假如在前端中有一个根据传入员工的姓名或性别或入职日期来进行员工查询的功能模块,按照以往的方式,我们可能会通过参数占位符写出如下处理语句:
@Select("select * from emp where name like concat('%','#{name}','%') and gender = #{gender} and entrydate between #{begin} and #{end}")
public void get(String name,Short gender,LocalDate begin,LocalDate end);
上述的这个例子,在信息填充完善的情况下是可以正常运行的。但是如果给入的的信息只有姓名,另外的都空着没填,那此时就出问题了,这个时候另外几项从前端就会传回null,数据库在检索的时候也会去查找字段值是null的记录。而正常的情况应该是没有填写内容的字段应该是不予检索的。此时就用到了动态SQL,我们可以根据传入参数的值来动态的决定哪些检索条件应该被拼接到SQL语句中。
二、动态SQL语句
1.if
< if > :用于判定条件是否成立。使用test属性进行条件判断,如果条件为true,则拼接if标签包裹的sql语句。
<if test = "条件表达式">
希望拼接的SQL语句
</if>
此时针对上面的例子我们就可以修改为:
//修改版1
//映射到XML文件中
<select id="get" resultType="com.it.pojo.Emp">
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>
</select>
2.where
修改版1虽然使用了动态if实现了检索条件的拼接,但事实上还有问题,例如我在检索时只输入了性别信息,其他都为空,则拼接到的SQL语句是这样的:
select * from emp where and gender = #{gender} //这里where之后直接and了,明显拼接有问题
针对上述问题,我们可以使用 < where > 标签来提到where关键字。
< where >只会在子元素有内容的情况下才会插入where字句,并且会自动去除子句开头的and和or关键字。
使用< where >关键字再做修改:
<select id="get" resultType="com.it.pojo.Emp">
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>
</where>
</select>
此时如果再一次只输入性别,而不给与其他属性值,则拼接结果为:
select * from emp where gender = #{gender} //这个时候就没有问题了
3.foreach
如果前端一次性传回一个集合,我们就需要使用< foreach >标签来进行处理
<foreach collection="集合名称" item="集合遍历出来的元素/项的别名" separator="每一次遍历使用的分隔符" open="遍历开始前拼接的片段" close="遍历结束后拼接的片段">
SQL语句
</foreach>
public void deleteByIds(List<Integer> ids);
<!--删除操作-->
<delete id="deleteByIds">
delete from emp where id in
<foreach collection="ids" item="id" separator="," open="(" close=")">
#{id}
</foreach>
以下是XML文件中的SQL:
以下为测试方法:在集合中一共传递了两个参数,分别为1,2
以下为控制台打印信息,可见Mybatis使用?进行了占位,然后再将参数进行的绑定:
总结
主要用于个人学习,如果存在错误还请大佬指正,小子拜谢。共勉。