在批量處理數據的時候可能會遇到同事需要操作一批數據,比如增刪改查。這個片博客記錄一下自己在操作過程中的方法和一些經驗。
如果在處理過程中使用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>