MyBatis 常用动态 SQL 标签?

MyBatis 面试题发布于

一、if

条件判断,满足则拼接 SQL 片段。

WHERE 1=1
<if test="name != null">AND name = #{name}</if>

二、where

自动去掉多余的 AND/OR,自动加 WHERE。

<where>
  <if test="name != null">AND name = #{name}</if>
</where>

三、set

用于 update,自动去掉多余逗号。

四、foreach

遍历集合,常用于 IN 查询和批量插入。

IN
<foreach collection="ids" item="id" open="(" separator="," close=")">
  #{id}
</foreach>

五、choose/when/otherwise

类似 switch-case。