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