1、原生批量插入 (性能好)
原生批量插入方法是依靠 MyBatis 中的 foreach 標簽,將數據拼接成一條原生的 insert 語句一次性執行的,核心實現代碼如下。
<insert id="insertBatch">
INSERT INTO sys_device_software(device_id,software_id) VALUES
<foreach collection="list" separator="," item="item">
(#{item.deviceId},#{item.softwareId})
</foreach>
</insert>
2、mybatis-plus批量插入方法 (簡單,不用寫SQL)
mybatis-plus批量插入功能核心實現類有三個:UserController(控制器)、UserServiceImpl(業務邏輯實現類)、UserMapper(數據庫映射類),它們的調用流程如下:

注意此方法實現需要先添加 MP 框架,打開 pom.xml 文件添加如下內容:
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>mybatis-plus-latest-version</version>
</dependency>
- controller實現:
public class UserController {
@Autowired
private UserServiceImpl userService;
/**
* 批量插入(自定義)
*/
@RequestMapping("/mysavebatch")
public boolean mySaveBatch(){
List<User> list = new ArrayList<>();
// 待添加(用戶)數據
for (int i = 0; i < 1000; i++) {
User user = new User();
user.setName("test:"+i);
user.setPassword("123456");
list.add(user);
}
return userService.saveBatchCustom(list);
}
}
- 業務邏輯層實現:
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper,User>
implements UserService {
@Autowired
private UserMapper userMapper;
public boolean saveBatchCustom(List<User> list){
return userMapper.saveBatchCustom(list);
}
}
- 持久層實現
@Mapper
public interface UserMapper extends BaseMapper<User>{
boolean saveBatchCustom(List<User> list);
}
兩種方法的性能對比,請參考:https://www.cnblogs.com/vipstone/p/15383065.html
