批量更新与插入,在代码中循环显然会影响效率。一般 的做法如下:
update
plan a
<update id="batchUpdateRule" parameterType="java.util.List">
<foreach collection="list" index="index" item="demo" separator=";">
update demo_table
<set>
<if test="demo.name != null">
name = #{demo.name,jdbcType=VARCHAR},
</if>
</set>
where id = #{demo.id,jdbcType=BIGINT}
</foreach>
</update>
plan b
update demo_table
<trim prefix="set" suffixOverrides=",">
<trim prefix="name=case" suffix="end,">
<foreach collection="list" item="demo">
<if test="demo.name!=null">
when id=#{demo.id} then #{demo.name}
</if>
</foreach>
</trim>
</trim>
<where>
<foreach collection="list" separator="or" item="demo">
id = #{demo.id}
</foreach>
</where>
insert
<insert id="batchInsert" parameterType="java.util.List">
insert into demo_table (
id,
name)
VALUES
<foreach collection="list" index="index" item="demo" separator=",">
(
#{demo.id,jdbcType=BIGINT},
#{demo.name,jdbcType=VARCHAR}
)
</foreach>
</insert>