在批量处理数据的时候可能会遇到同事需要操作一批数据,比如增删改查。这个片博客记录一下自己在操作过程中的方法和一些经验。
如果在处理过程中使用IN,那么要注意如果IN后边的参数超过1000,数据库会报错。我是直接用逻辑代码把数据量控制在1000以内,具体可以参考上一篇博客的方法。
接下来贴上增删改的mybatis代码:
增加:
<insert id="insertList" parameterType="java.util.List">
insert into tableName (ID, NAME, AGE)
<foreach collection="list" item="item" index="index" open="(" close=")" separator="union all">
select #{item.id,jdbcType=VARCHAR}, #{item.name,jdbcType=VARCHAR},
#{item.age,jdbcType=VARCHAR}
from dual
</foreach>
</insert>
删除:
<delete id="deleteList" parameterType="java.util.List">
delete from TABLENAME
where ID in
<foreach collection="list" item="item" index="index" open="(" separator="," close=")">
#{item,jdbcType=VARCHAR}
</foreach>
</delete>
修改:
<update id="updateList" parameterType="java.util.List">
<foreach collection="list" item="item" index="index" open="begin" close=";end;" separator=";">
update TABLENAME
<set>
<if test="item.name!= null">
NAME = #{item.name,jdbcType=VARCHAR},
</if>
<if test="item.age!= null">
AGE = #{item.age,jdbcType=VARCHAR},
</if>
</set>
where ID = #{item.id,jdbcType=VARCHAR}
</foreach>
</update>
本文分享了在批量处理数据时,如何避免数据库因参数过多而报错的问题,通过控制数据量和使用MyBatis进行增删改操作的具体实现方法。
1894

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



