Mybatis的修改(update)操作
一、口诀记忆
口诀:
> 动态SQL用<set>,条件判断靠<if>,
> 字段非空才更新,where主键别忘记。
二、知识点表格
| 步骤 | 关键点 | 说明/示例 |
|--------------|----------------------|--------------------------------------------------------------------|
| 1. Mapper接口 | 参数用对象封装 | void update(User user); |
| 2. SQL映射 | <set>+<if>动态拼接 | <set><if test="xx!=null">xx=#{xx},</if></set> |
| 3. where条件 | 主键不能少 | where id=#{id} |
| 4. 测试 | 只传需要修改的字段 | 只传username,只有username会被更新 |
三、代码模板
1. Mapper接口
void update(User user);
2. 映射文件(XML)
<update id="update">update tb_user<set><if test="username != null and username != ''">username = #{username},</if><if test="password != null and password != ''">password = #{password},</if><!-- 其他字段同理 --></set>where id = #{id}
</update>
四、易错点提醒
- 不要忘记<set>标签,它会自动去掉最后一个逗号。
- where条件必须有主键,否则会全表更新,危险!
- 判断条件要写全,如!= null and != '',防止空字符串也被更新。
五、流程图(简化版)
- 接收前端传来的对象
- 只对非空字段生成SQL
- 根据主键id定位要修改的数据
- 执行更新
六、记忆小结
- 动态SQL = <set> + 多个<if>
- 只更新有值的字段
- where主键条件必不可少