在处理数据的时候,用mybatis 要进行批量插入,还要根据字段更新关联表的字段内容。记录下如何使用的。
mapper:
void insertBatchDispatch(@Param("dispatches") List dispatches) ;
xml:
- <sql id="DispatchColumn">
- DISPATCH_ID, SERVICE, CIRCUIT, ROUTE
- sql>
-
- <insert id="insertBatchDispatch" parameterType="java.util.List">
- insert into dispatch_service
- ( <include refid="DispatchColumn">include> )
- values
- <foreach collection ="dispatches" item="item" separator =",">
- (#{item.dispatchId}, #{item.service},
- #{item.circuit}, #{item.route})
-
- insert>
如何一次性插入很多,会执行报错。可以分批插入,插入个1000条
分批数据处理可以用skip和limit
参考:
- public static void main(String args[]) {
- String data = "1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20";
- List
datas = Arrays.asList(data.split(",")); - System.out.println(datas.size() + " "+JSON.toJSONString(datas));
- int loopSize = 3;
- int dataSize = datas.size();
- // 向上取整
- int loop = dataSize / loopSize + (dataSize % loopSize != 0 ? 1 : 0);
-
- System.out.println(loop);
- for (int i = 0; i < loop; i++) {
- List
skipData = ListUtils.emptyIfNull(datas).stream().skip(i * loopSize).limit(loopSize).collect(Collectors.toList()); - System.out.println(skipData);
- }
- }
如何进行批量修改呢?
mapper:
void updateBatchDetail(@Param("details") List details) ;
xml:
- <update id="updateBatchDetail" parameterType="java.util.List">
- <foreach collection="details" item="item" index="index" open="" close="" separator=";">
- update circuit_detail
- set service = #{item.service,jdbcType=VARCHAR},
- circuit = #{item.circuit,jdbcType=VARCHAR},
- route = #{item.route,jdbcType=VARCHAR}
- where dispatch_id = #{item.dispatchId}
- foreach>
- update>
执行报错,怎么处理呢?
mybatis支持批量操作
开启批量执行sql的开关,在拼装mysql链接的url时,为其加上allowMultiQueries参数,设置为true,即allowMultiQueries=true,如下:
mysql
jdbc.jdbcUrl=jdbc:mysql://127.0.0.1:3306/databaseName?useUnicode=true&characterEncoding=utf8&allowMultiQueries=true
sqlserver
datasource.url=jdbc:sqlserver://127.0.0.1:1433;DatabaseName=databaseName;allowMultiQueries=true
批量插入和批量修改,要注意控制数量,批量修改要记得开启批量执行的操作,在连接的url上添加allowMultiQueries=true