目录
1.if
1.1 条件查询,如参数非空则执行条件:
<select id=\"getByUserName\" parameterType=\"string\" resultMap=\"sysUserResultMap\">
SELECT * FROM sys_user T
<where>
<if test=\"_parameter !=null and _parameter !=\'\' \">
USER_NAME = #{value}
</if>
</where>
</select>
2.choose(when、otherwise)
2.1 有时我们不想应用到所有的条件语句,而只想从中择其一项。针对这种情况,MyBatis 提供了 choose 元素,它有点像 Java 中的 switch 语句。如根据用户名和身份证查询,两者非空则根据状态查询:
<select id=\"getByUserCnNameOrIdCard\" parameterType = \"SysUser\" resultMap = \"sysUserResultMap\">
SELECT * FROM sys_user T WHERE 1=1
<choose>
<when test=\"userCnName != null and userCnName !=\'\' \">
AND USER_CN_NAME like CONCAT(\'%\',\'${userCnName}\',\'%\')
</when>
<when test=\"idCard !=null and idCard != \'\' \">
AND IDCARD = #{idCard}
</when>
<otherwise>
AND STATUS = 2
</otherwise>
</choose>
</select>
3.where
<select id=\"getByUuid\" parameterType=\"string\" resultMap=\"sysUserResultMap\">
SELECT * FROM sys_user T
<where>
<if test=\"_parameter !=null and _parameter !=\'\' \">
UUID = #{value}
</if>
</where>
</select>
4.set
4.1 动态包含需要更新的列而摄取其他的,如更新用户信息操作:
<update id=\"edit\" parameterType = \"SysUser\">
UPDATE sys_user
<set>
<if test=\"userName !=null and userName !=\'\' \">
USER_NAME = #{userName}
</if>
<if test=\"password !=null and password !=\'\' \">
PASSWORD = #{password}
</if>
<if test=\"userCnName !=null and userCnName !=\'\' \">
USER_CN_NAME = #{userCnName}
</if>
<if test=\"idCard !=null and idCard !=\'\' \">
IDCARD = #{idCard}
</if>
<if test=\"phone !=null and phone !=\'\' \">
PHONE = #{phone}
</if>
<if test=\"email !=null and email !=\'\' \">
EMAIL = #{email}
</if>
<if test=\"imageUrl !=null and imageUrl !=\'\' \">
IMAGE_URL = #{imageUrl}
</if>
<if test=\"address !=null and address !=\'\' \">
ADDRESS = #{address}
</if>
<if test=\"status !=null and status !=\'\' \">
STATUS = #{status}
</if>
<if test=\"createTime !=null and createTime !=\'\' \">
CREATE_TIME = #{createTime}
</if>
</set>
WHERE UUID = #{uuid}
</update>
5.foreach
5.1动态 SQL 的另外一个常用的操作需求是对一个集合进行遍历,通常是在构建 IN 条件语句的时候,如根据id集合查询多用户:
<select id=\"getUsersByIdList\" parameterType = \"list\" resultMap = \"sysUserResultMap\">
SELECT * FROM sys_user WHERE UUID IN
<foreach collection=\"list\" item = \"item\" index = \"index\"
open=\"(\" separator = \",\" close = \")\" >
#{item}
</foreach>
</select>
6.bind
6.1 bind 元素可以从 OGNL 表达式中创建一个变量并将其绑定到上下文,如模糊查询:
<select id=\"selectUserLike\" parameterType=\"SysUser\" resultType=\"SysUser\">
<bind name=\"pattern\" value=\"\'%\' + userName + \'%\'\" />
SELECT * FROM sys_user
WHERE USER_NAME LIKE #{pattern}
</select>
继续阅读与本文标签相同的文章
上一篇 :
一文看懂上海区块链布局
-
学宏程序编程,这些知识必不可少!
2026-05-14栏目: 教程
-
华为准备卖出“落后”的5G,多家美企极力竞争!任正非格局太大!
2026-05-14栏目: 教程
-
百度:飞桨深度学习平台已累计服务150多万开发者
2026-05-14栏目: 教程
-
滴滴公布安全功能数据:近2亿用户添加紧急联系人
2026-05-14栏目: 教程
-
滴滴自动驾驶或将于年底落地上海
2026-05-14栏目: 教程
