使用hutool分割list
import cn.hutool.core.collection.CollUtil;
public ReturnT batchInsert() {
List list = new ArrayList<>();
for (int i = 0; i < 100; i++) {
SysUserDTO sysUserDTO = new SysUserDTO();
sysUserDTO.setUsername("admin" + i);
sysUserDTO.setPassword("12345" + i);
sysUserDTO.setUserAccount("admin" + i);
sysUserDTO.setEmail("admin" + i + "@163.com");
sysUserDTO.setCreateBy("admin");
list.add(sysUserDTO);
}
int size = 100;
int total = 0;
List> lists = CollUtil.splitList(list, size);
for (List sysUserDTOS : lists) {
int rows = baseMapper.insertBatch(sysUserDTOS);
total += rows;
}
return new ReturnT<>(total);
}
public ReturnT updateBatch() {
List list = new ArrayList<>();
for (int i = 0; i < 100; i++) {
SysUserDTO sysUserDTO = new SysUserDTO();
sysUserDTO.setUsername("admin200" + i);
sysUserDTO.setPassword("12345" + i);
sysUserDTO.setUserAccount("admin" + i);
sysUserDTO.setEmail("admin" + i + "@163.com");
sysUserDTO.setCreateBy("admin");
list.add(sysUserDTO);
}
int size = 100;
int total = 0;
List> lists = CollUtil.splitList(list, size);
for (List sysUserDTOS : lists) {
int rows = baseMapper.updateBatch(sysUserDTOS);
total += rows;
}
return new ReturnT<>(total);
}
List> lists = CollUtil.splitList(list, size);
1. 批量新增
INSERT INTO `sys_user`(`username`, `password`, `user_account`, `email`, `salt`, `phone`, `create_time`,
`create_by`)
VALUES
(#{sysUser.username}, #{sysUser.password}, #{sysUser.userAccount}
,#{sysUser.email},#{sysUser.salt},#{sysUser.phone}
,now(),#{sysUser.createBy}
)
2. 批量更新
需要建唯一索引
INSERT INTO `sys_user`(`username`, `password`, `user_account`, `email`, `salt`, `phone`, `create_time`,
`create_by`)
VALUES
(#{sysUser.username}, #{sysUser.password}, #{sysUser.userAccount}
,#{sysUser.email},#{sysUser.salt},#{sysUser.phone}
,now(),#{sysUser.createBy}
)
ON DUPLICATE KEY UPDATE
id=VALUES(id),username = VALUES(username),password = VALUES(password),user_account = VALUES(user_account),
email = VALUES(email),salt = VALUES(salt),phone = VALUES(phone),
create_time = VALUES(create_time),create_by = VALUES(create_by)