【笔记】MyBatis动态SQL语句

前言

Mybatis构造动态SQL语句

if判断语句

  • 判断传递过来的值是否为不空,当不为空时才执行SQL

xxxXxx:从Java传递来的变量

1
2
3
<if test="xxxXxx != null and xxxXxx != ''">
...
</if>

choose选择语句

  • 满足条件的<when></when>被执行,
    • <choose></choose>相当于switch
    • <when></when>相当于case
    • <otherwise></otherwise>相当于default
      • 如果没有想要拼接的<otherwise></otherwise>,可以用1=1占位
1
2
3
4
5
6
7
8
9
10
WHERE
<choose>
<when test="xxxXxx != null and xxxXxx != ''">
xxx_xxx = #{xxxXxx}
</when>
...
<otherwise>
1 = 1
</otherwise>
</choose>

动态where子句嵌套

1
2
3
4
5
6
7
8
9
10
11
<where>
<choose>
<when test="xxxXxx != null and xxxXxx != ''">
xxx_xxx = #{xxxXxx}
</when>
...
<otherwise>
1 = 1
</otherwise>
</choose>
</where>

用于修剪的语句

利用sql语句解决多余的and或or

1
2
3
4
5
where 1=1
<if test="xxxXxx != null">
AND xxx_xxx = #{xxxXxx}
</if>
...

动态拼接where子句

  • 通常用在SELECT * FROM table_name where xxx=xxx ...
  • <where></where>可以自动去除首个多余的ANDOR

完全匹配

1
2
3
4
5
6
<where>
<if test="xxxXxx != null">
AND xxx_xxx = #{xxxXxx}
</if>
...
</where>

模糊匹配

  • 直接在关键字前后添加百分号会报错,可以从mybatis层面或者sql层面拼接字符串,以解决问题
通过mybatis标签
1
2
3
4
5
6
7
<where>
<if test="xxxXxx != null">
<bind name="xxxXxx" value="'%' + xxxXxx + '%'" />
AND xxx_xxx LIKE #{xxxXxx}
</if>
...
</where>
通过sql函数
1
2
3
4
5
6
<where>
<if test="xxxXxx != null">
AND xxx_xxx LIKE concat('%', #{xxxXxx}, '%')
</if>
...
</where>

动态拼接set子句

  • 通常用在UPDATE table_name xxx=xxx ....语句
  • <set></set>可以自动去除末尾多余的,
1
2
3
4
5
6
<set>
<if test="xxxXxx != null">
xxx_xxx = #{xxxXxx},
</if>
...
</set>

trim动态拼接小括号

  • 通常用在INSERT INTO table_name (...) VALUES (...)语句
1
2
3
4
5
6
<trim prefix="(" suffix=")" suffixOverrides=",">
...
</trim>
<trim prefix="VALUES (" suffix=")" suffixOverrides=",">
...
</trim>

foreach用于遍历Java集合的语句

  • 通常用在SELECT * FROM table_name ... AND (xxx=xxx OR xxx=xxx)语句

collection=""

array:MyBatis底层会自动将Java中传递的数组作为Map的值,而Map的键为array
xxxXxx:如果一定要使用Java数组名,那么需要在接口中使用@Param()注解重新指定参数名

1
2
3
4
IN 
<foreach collection="xxxXxx" item="xxxXxxOne" open="(" close=")" separator=",">
#{xxxXxxOne}
</foreach>

完成

参考文献

CSDN——weixin_33921089
CSDN——走路的猫头鹰
哔哩哔哩——黑马程序员