1. 方法参数定义
首先在Mapper接口中定义方法,使用@Param注解明确参数名:
int dynamicUpdate(
@Param("tableName") String tableName,
@Param("updateFields") Map<String, Object> updateFields,
@Param("conditionFields") Map<String, Object> conditionFields
);
2. XML动态SQL实现
在Mapper.xml中使用<update>标签和动态SQL标签(如<if>、<foreach>)实现动态拼接:
<update id="dynamicUpdate">
UPDATE ${tableName}
<!-- 动态SET字段 -->
<set>
<foreach collection="updateFields" index="field" item="value" separator=",">
<if test="value != null">
${field} = #{value}
</if>
</foreach>
</set>
<!-- 动态WHERE条件 -->
<where>
<foreach collection="conditionFields" index="field" item="value">
AND ${field} = #{value}
</foreach>
</where>
</update>
3. 方法调用示例
Map<String, Object> updateFields = new HashMap<>();
updateFields.put("name", "张三");
updateFields.put("age", 25);
Map<String, Object> conditionFields = new HashMap<>();
conditionFields.put("id", 1);
mapper.dynamicUpdate("user_table", updateFields, conditionFields);
4. 生成的实际SQL
UPDATE user_table
SET name = '张三', age = 25
WHERE id = 1

2206

被折叠的 条评论
为什么被折叠?



