目录
Mybatis 动态SQL 可以在xml映射文件内,以标签的形式编写动态SQL,执行原理是根据表达式的值完成逻辑判断并动态拼接SQL的功能。
mybatis提供了9种动态SQL标签:trim、where、set、foreach、if、choose、when、otherwise 。
1.if
if + where 常用于 select 查/删
<select id="findListByMap" resultMap="resultUser">
select * from smbms_user where 1=1
<if test="userCode != NULL">
and userCode like concat('%',#{userCode},'%')
</if>
</select>
<resultMap id="resultUser" type="User">
<id property="name" column="userName"></id>
</resultMap>
2.if+trim
if+trim 常用于 增
<select id="findListByMap" resultMap="resultUser">
select * from smbms_user
<trim prefix="where" suffixOverrides="and">
<if test="userCode != NULL">
userCode like concat('%',#{userCode},'%')
</if>
</trim>
</select>
trim标签用途用于拼接
- prefix 给sql语句拼接的前缀(整体)
- suffix 给sql语句拼接的后缀
- prefixOverrides 去除sql语句前面的关键字或者字符,该关键字或者字符由 prefixOverrides 属性指定,假设该属性指定为"AND",当sql语句的开头为"AND",trim标签将会去除该"AND"
- suffixOverrides 去除sql语句后面的关键字或者字符,该关键字或者字符由suffixOverrides属性指 定。
3.if+set
if+set 常用于 update 改
<update id="updateUser">
update smbms_user
<set>
<if test="userCode != null">userCode = "zhangsan",</if>
<if test="userPassword != null">userPassword = "123123",</if>
</set>
where id = #{id}
</update>
4.foreach
foreach 一般用于 in 函数
<select id = "findById" parameterType = "list" resultType = "user">
select * from user
<where>
<foreach item = "id" collection = "list" open = "id in (" separator = "," close = ")" >
#{id}
</foreach>
</where>
</select>
item : 循环后获取的每个对象值
collection : 指定循环集合类型 list,array ,map-key
open: 前缀
close: 后缀
separator: 中间以什么隔开
5.choose(when otherwise)
<choose>
<when test = "条件1">...</when>
<when test = "条件2">...</when>
<when test = "条件3">...</when>
...
<otherwise>...</otherwise>
</choose>
MyBatis 中动态语句 choose-when-otherwise 类似于 Java 中的 switch-case-default 语句。
由于 MyBatis 并没有为 if 提供对应的 else 标签,如果想要达到…… 的效果,可以借助 、、 来实现。