简介
在朋友咨询之下,如何快速处理mybatis批量入库问题,个人也探索一下,并写成组件化。个人这里主要讲解foreach批量入库操作
功能实现
编写 mapper
test表
CREATE TABLE `test` (
`id` int(11) NOT NULL,
`name` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
pojo文件
@Alias("test")
@Getter
@Setter
public class Test {
private Integer id;
private String name;
}
TestMapper.xml文件
<insert id="insertBatch" parameterType="list">
insert into test(id,name) values
<foreach collection ="paramList" item="param" separator = ",">
(#{param.id},#{param.name})
</foreach>
</insert>
分批处理类
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.function.Function;
/**
* @author guohu
*/
public class SubInvokeUtil {
/**
* 分段处理器
* @param invoke 入参匿名函数
* @param params 入参集合
* @param limitCount 每批处理个数
* @return
*/
public static <T, R> List<R> subInvoke(Function<List<T>, R> invoke, List<T> params, int limitCount) {
List<R> resultList = new ArrayList<>();
Object[] arrayParams = params.toArray();
int size = params.size();
if (size > limitCount) {
int count = Objects.equals(size % limitCount,0) ? size / limitCount : size / limitCount + 1;
for (int batchNum = 0; batchNum < count; batchNum++) {
int srcPos = batchNum * limitCount;
if (Objects.equals(count - 1,batchNum) && srcPos + limitCount > size) {
limitCount = size - srcPos;
}
Object[] subList = new Object[limitCount];
System.arraycopy(arrayParams, srcPos, subList, 0, limitCount);
resultList.add(invoke.apply(Arrays.asList((T[]) subList)));
}
} else {
resultList.add(invoke.apply(params));
}
return resultList;
}
}
测试
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBatchInsertTests {
@Resource
private TestMapper testMapper;
@Test
public void insertBatch() {
List<Test> list = new ArrayList<>();
Test test1 = new Test();
test1.setId(11511);
test1.setName("张三12");
list1.add(test1);
Test test2 = new Test();
test2.setId(1121);
test2.setName("张三13");
list.add(test2);
Test test3 = new Test();
test3.setId(13);
test3.setName("张三15");
list.add(test3);
SubInvokeUtil.subInvoke(params->testMapper.insertBatch(params),list,2);
System.out.println();
}
}
参考文献
【1】 三种入库操作