mybatis中进行批量插入的sql示例:
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" > <mapper namespace="com.pisen.cloud.luna.ms.jifen.base.mapper.ShelfLogDetailMapper"> <insert id="batchSave"> INSERT INTO shelf_log_detail (auto_shelf,shelf_type,operator_id,operator_date,tid,brand_uid,integral_goods_id,integral_goods_name,market_value, integral,integral_goods_type,stock,sale_num,integral_goods_code,specification)
VALUES
<foreach collection="list" item="item" separator=","> (#{item.autoShelf},#{item.shelfType},#{item.operatorId},#{item.operatorDate},#{item.tid},#{item.brandUid},#{item.integralGoodsId}, #{item.integralGoodsName},#{item.marketValue},#{item.integral},#{item.integralGoodsType},#{item.stock}, #{item.saleNum},#{item.integralGoodsCode},#{item.specification}) </foreach> </insert> </mapper>
为了放置sql拼接过长,还有事务的高效性,可以进行切割批量插入
示例代码:【list切割的方法查看:https://www.cnblogs.com/sxdcgaq8080/p/9376947.html】
/** * 批量插入 * @param source * @param autoShelf * @param shelfType */ private void batchInsert(List<String> source,Integer autoShelf,Integer shelfType){ Date date = new Date(); List<List<String>> result = ListUtils.splitListBycapacity(source,50); if (result != null){ for (List<String> strings : result) { List<ShelfLogDetail> logDetailList = mapper.findList(strings); for (ShelfLogDetail logDetail : logDetailList) { logDetail.setOperatorDate(date); logDetail.setAutoShelf(autoShelf); logDetail.setShelfType(shelfType); } shelfLogDetailMapper.batchSave(logDetailList); } } }