Mybatis中的两个动态SQL标签
目录
功能对比
代码示例
实际效果
如何选择
总结
在Mybatis中,
<trim> and <set>
都是动态SQL标签,用于处理更新操作中的条件拼接。以下是它们的区别和适用场景:
功能对比
特性 | <trim>实现 | <set>实现 |
---|---|---|
标签用途 | 通用标签,可自定义前缀、后缀和覆盖规则。 | 专为 UPDATE 设计的简化标签,自动处理 SET 和逗号。 |
前缀 | 需手动指定 prefix="set"。 | 自动添加 SET 关键字。 |
后缀处理 | 需手动指定 suffixOverrides="," 去除多余逗号。 | 自动去除最后一个逗号。 |
灵活性 | 更高,可用于其他场景(如 WHERE 条件拼接)。 | 仅适用于 UPDATE 的 SET 部分。 |
代码示例
<update id="trimUpdate" parameterType="com.qcby.entity.User">update user<trim prefix="set" suffixOverrides=","><if test="username != null and username != ''">username = #{username},</if><if test="birthday != null">birthday = #{birthday},</if><if test="address != null and address != ''">address = #{address},</if><if test="password != null and password != ''">password = #{password},</if></trim>where id = #{id}
</update>
- 手动配置:
- prefix = "set":在条件前加“set”关键字
- suffixOverrides = “,”:自动去除末尾多余的逗号
<update id="update" parameterType="com.qcby.entity.User">update user<set><if test="username != null and username != ''">username = #{username},</if><if test="birthday != null">birthday = #{birthday},</if><if test="address != null and address != ''">address = #{address},</if><if test="password != null and password != ''">password = #{password},</if></set>where id = #{id}
</update>
- 自动处理:
- 自动添加“set”关键字
- 自动去除最后一个逗号
实际效果
假设 User 对象只有 username 和 password 非空,生成的SQL如下:
/*trimUpdate:*/
update user
SET username = '张三', password = '123456'
where id = 1;/*update:*/
update user
SET username = '张三', password = '123456'
where id = 1;
两者生成的SQL完全一致,但 “set” 的实现更简洁
如何选择
- 使用set:
- 专为 update 设计,代码更简洁,推荐在大多数更新场景中使用
- 使用trim:
- 需要更灵活的拼接(如动态 where 或混合逻辑时),或需要自定义前缀后缀时使用
总结
场景 | 推荐标签 | 原因 |
---|---|---|
标准 UPDATE 操作 | set | 语法简洁,自动处理 SET 和逗号。 |
复杂动态 SQL | trim | 灵活控制前缀、后缀和覆盖规则(如同时处理 SET 和 WHERE 条件拼接)。 |
根据实际需求选择即可,功能上两者在 update 中等价,但 set 可读性更优