個人收藏使用
文章來自Mybatis 中傳入List實現(xiàn) 批量插入、批量更新、批量刪除 - chelsey3tsf - 博客園 (cnblogs.com)
1. 批量插入:
Mapper層:
int insertList(List<UsersModel> list);
對應的mapper.xml:
<!--批量插入信息--> <insert id="insertList" parameterType="java.util.List"> insert into users( id, name ) values <foreach collection="list" item="item" index="index" separator=","> ( #{id,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR} ) </foreach> </insert>
如果List數(shù)據(jù)量比較大,可以考慮將List分批次插入
2. 批量更新:
批量更新只提供更新單個字段的,因為更新多個字段無論哪種批量更新方案,我都用起來很不舒服,所以不做提供。
Mapper層:
int updateList(List<AgentApply> list);
對應的mapper.xml:
<!--批量更新--> <update id="updateList" parameterType="java.util.List"> update agent_apply set apply_time= <foreach collection="list" item="item" index="index" separator=" " open="case" close="end"> when id=#{item.id} then #{item.applyTime} </foreach> where id in <foreach collection="list" index="index" item="item" separator="," open="(" close=")"> #{item.id,jdbcType=INTEGER} </foreach> </update>
3. 批量刪除:
PS:一般查詢出來的List都是包含對象在里面的,那么怎么清理出單獨包含ID的list呢?
可以參考下面方式,第一個listData是從數(shù)據(jù)庫查詢出來的list數(shù)據(jù),每個元素都是一個對象;
然后單獨把里面每個元素的id給取出來放入新的list(ids)。
List<AgentRechargeOrder> listData = agentRechargeOrderServiceImpl.getListByXXXX(XXXX); List<Integer> ids = listData.stream().map(AgentRechargeOrder::getId).collect(Collectors.toList());
如果不想清除出單獨的id的list,直接傳整個List也是可以的, 這樣mapper層傳值就改成對應的包含對象的List即可。
Mapper層:
int deleteMany(List<Integer> ids);
對應的mapper.xml:
<delete id="deleteMany"> delete from agent_recharge_order where id in <foreach collection="list" item="item" open="(" separator="," close=")"> #{item} </foreach> </delete>
最后補充個提醒:
因為批量操作會拼接成很長很長的mysql語句,所以mysql server在接收數(shù)據(jù)包的時候,對這個數(shù)據(jù)包的大小是有設置項限制的。
如果超過設置的值,就會報錯:文章來源:http://www.zghlxwxcb.cn/news/detail-512852.html
Caused by: com.mysql.jdbc.PacketTooBigException: Packet for query is too large
那么就需要修改這個設置項,所以推薦提前先把對應的設置值稍微弄大一點文章來源地址http://www.zghlxwxcb.cn/news/detail-512852.html
到了這里,關于Mybatis 中傳入List實現(xiàn) 批量插入、批量更新、批量刪除的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!