Mybatis 使用foreach标签和set标签写一个update
时间: 2024-01-24 22:03:00 浏览: 159
示例:
假设有一个User表,有一个字段为status,需要更新多条记录的status值为1,更新的记录id为1、2、3,可以使用以下代码:
```
<update id="updateUserStatus">
UPDATE User
SET status = 1
<where>
<foreach collection="ids" item="id" separator="OR">
id = #{id}
</foreach>
</where>
</update>
```
其中,ids为一个List类型的参数,存储需要更新的记录的id值。在where标签内使用foreach标签循环遍历ids中的id值,将每个id值拼接为OR条件,最终得到的sql语句如下:
```
UPDATE User
SET status = 1
WHERE id = 1 OR id = 2 OR id = 3
```
如果需要更新多个字段,可以使用set标签,示例代码如下:
```
<update id="updateUser">
UPDATE User
<set>
<foreach collection="params" item="param" separator=",">
<if test="param.name != null">name = #{param.name}</if>
<if test="param.age != null">age = #{param.age}</if>
<if test="param.tel != null">tel = #{param.tel}</if>
</foreach>
</set>
<where>
<foreach collection="ids" item="id" separator="OR">
id = #{id}
</foreach>
</where>
</update>
```
其中,params为一个List类型的参数,存储需要更新的字段和值,示例代码中更新的字段为name、age、tel。在set标签内使用foreach标签循环遍历params中的每个param对象,如果该字段不为null,则拼接为update语句中的一个字段更新语句。最终得到的sql语句如下:
```
UPDATE User
SET name = 'xxx', age = 20, tel = 'xxx'
WHERE id = 1 OR id = 2 OR id = 3
```
阅读全文
相关推荐


















