MyBatis提供了foreach標簽來實現批量更新操作,以下是使用foreach標簽進行批量更新的幾個技巧:
<update id="batchUpdate" parameterType="java.util.List">
update table_name
set column1 = #{list[0].column1},
column2 = #{list[0].column2}
where id in
<foreach collection="list" item="item" index="index" separator="," open="(" close=")">
#{item.id}
</foreach>
</update>
<update id="batchUpdate" parameterType="java.util.Map">
update table_name
<set>
<foreach collection="map.entrySet()" item="entry" separator=",">
${entry.key} = #{entry.value}
</foreach>
</set>
where id in
<foreach collection="ids" item="id" separator="," open="(" close=")">
#{id}
</foreach>
</update>
<update id="batchUpdate" parameterType="java.util.List">
update table_name
<set>
<foreach collection="list" item="item" separator=",">
<if test="item.column1 != null">column1 = #{item.column1}</if>
<if test="item.column2 != null">column2 = #{item.column2}</if>
</foreach>
</set>
where id in
<foreach collection="list" item="item" separator="," open="(" close=")">
#{item.id}
</foreach>
</update>
通過上述技巧,可以靈活地使用foreach標簽實現批量更新操作,提高MyBatis的操作效率。