这里自己写了个对集合按一批的数量进行分批操作的分页bean,见PagenationUtil如下:
package com.util; import java.util.List ; /** * @author kyoxue * @date 2018年05月31日 * @param <E> 集合存放的实体类型 */ public class PagenationUtil<E> { /** * 分页的集合 */ private List<E> list = null; /** * 当前页 */ private int page =0; /** * 每页大小 */ private int pageSize =0; /** * 集合总条数 */ private int totalCount =0; /** * 总页数 */ private int totalPage =0; /** * @param list 数据集合 * @param pageSize 分页大小 */ public PagenationUtil(List<E> list,int pageSize){ this.list = list ; this.pageSize = pageSize ; this.totalCount = ((null == list || list.size() == 0)?0:list.size()); this.totalPage = totalCount>0?((totalCount + pageSize - 1) / pageSize):0; } public List<E> getPageList(){ if (totalCount == 0) { return null; } if (pageSize == 0) { return null; } int total = getTotalPage(); int current = getPage(); if (current > total) { return null; } if (current <= 0) { return null; } int start = pageSize*(current-1); if (current == total) { int leftLen = totalCount%pageSize; if (leftLen>0) { return list.subList(start, start+leftLen); } } return list.subList(start, start+pageSize); } public int getPage() { return page; } public void setPage(int page) { this.page = page; } public int getTotalPage(){ return this.totalPage; } }
mybatis分批插入(mapper接口与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.dao.XxxMapper" > <insert id="insertBatch" parameterType="java.util.ArrayList"> insert into t_xx(xx,yy) values <foreach collection="list" item="item" index="index" separator=","> (#{item.xx},#{item.yy}) </foreach> </insert> </mapper>
public interface XxxMapper { void insertBatch(List<Xx> list); }
使用自己写的PagenationUtil,对数据集合进行分批执行sql:
PagenationUtil<XX> pageutil = new PagenationUtil<Xx>(集合, 批次数量); int totalPage = pageutil.getTotalPage(); for (int i = 1; i < totalPage+1; i++) { pageutil.setPage(i); List<Xx> each = pageutil.getPageList(); xxMapper.insertBatch(each); }