开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第1天
动态SQL
动态SQL是MyBatis的强大特性之一,省去了单一SQL语句的反复堆砌,提高其复用性
动态SQL的常用元素
| 元素 | 说明 |
|---|---|
| 判断语句,用于单条件判断 | |
| (、) | 相当于switch语句,用于多条件判断 |
| 简化SQL语句种where的条件判断 | |
| 可以灵活地去除多余的关键字 | |
| 用于SQL语句的动态更新 | |
| 循环语句,常用于in语句等列举条件中 |
if应用举例
例:要查找学生信息,可以通过姓名和学号来查询学生,也可以只填写一个条件,只使用学号或姓名来查询学生,还可以都不填写,输出所有学生,此时的姓名和学号就为非必需条件
select * from t_student where 1=1
<if test="studentname!=null and studentname!=''">
and username like concat('%',#{studentname},'%')
</if>
<if test="num!=null and num!=''">
and num=#{num}
</if>
choose、when、otherwise应用举例
例:当学生姓名不为空时,根据学生姓名进行筛选;当姓名为空,而学号不为空时,只根据学号进行筛选;当姓名与学号均为空时,要求查找出所有住址不为空的学生信息
针对上述案例,使用if进行处理是不合适的,我们则使用choose、when、otherwise进行操作
select * from t_student where 1=1
<choose>
<when test="studentname!=null and studentname!=''">
and studentname like concat('%',#{studentname},'%')
</when>
<when test="num!=null and num!=''">
and num=#{num}
</when>
<otherwise>
and addr is not null
</otherwise>
</choose>
where和trim
我们上面写判断语句都要加一个 where 1=1 以起到后续连接的作用,但这样很麻烦又显得很奇怪,于是where可以替我们实现判断,让我们省去这一步。
where会自动判断语句,只有where内的一个或多个条件成立时,才会在SQL中加入where关键字,否则将不会添加;还会去除多余的"and" 或 "or"
而trim功能更加强大,可以实现添加和去除两种功能,它的prefix属性代表语句的前缀,prefixOverrides属性代表去除的前缀字符串。suffix和suffixOverrides则是表示后缀。
set
在Hibernate框架中,如果想要更新某一个对象,就需要发送所有字段给持久化对象,但在实际应用中,大多数情况下都是更新某一个或某几个字段,于是我们有了set元素,用于更新操作,它负责在动态SQL语句前输出一个SET关键字,并将SQL语句中最后一个多余的逗号去除
<update id="updateStudent" parameterType="com.hexiaoxing.po.Student">
update t_student
<set>
<if test="studentname!=null and studentname!=''">
studentname=#{studentname},
</if>
<if test="num!=null and num!=''">
num=#{num},
</if>
</set>
where id=#{id}
</update>
foreach
当我们要批量查询数据,比如查询学号位于前一百位的学生,如果从1开始,一条一条查询显然很繁琐,这里我们使用foreach进行循环遍历
| 属性 | 说明 |
|---|---|
| item | 表示集合中每一个元素进行迭代时的别名。必选 |
| index | 在List和数组中,index是元素的序号,在Map中,index是元素的key。可选 |
| open | 表示foreach语句代码的开始符号,一般和close=")"合用。常在in条件语句中。可选 |
| separator | 表示元素之间的分隔符。可选 |
| close | 表示foreach语句代码的关闭符号,一般和open="("合用。常在in条件语句中。可选 |
| collection | 用于指定遍历参数的类型。必须 |
举例:
<select id="findByArray"
parameterType="java.util.Arrays"
resultType="com.itheima.pojo.Student">
select * from t_student where id in
<foreach item="id" index="index" collection="array"
open="(" separator="," close=")">
#{id}
</foreach>
</select>