MybatisPlus自带的批量插入为伪批量插入,故此我们自定义批量插入方法
1. 新建InsertBatchSqlInjector类
/**
* 自定义批量插入 SQL 注入器,Mybatis-Plus自带的saveBatch为伪批量插入
*/
public class InsertBatchSqlInjector extends DefaultSqlInjector {
@Override
public List<AbstractMethod> getMethodList(Class<?> mapperClass, TableInfo tableInfo) {
// super.getMethodList() 保留 Mybatis Plus 自带的方法
List<AbstractMethod> methodList = super.getMethodList(mapperClass, tableInfo);
// 添加自定义方法:批量插入,方法名为 insertBatchSomeColumn
methodList.add(new InsertBatchSomeColumn());
return methodList;
}
}
2. 新建MybatisPlusConfig类
@Configuration
@MapperScan("online.shenjian.cloud.**.mapper")
public class MybatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
// 分页用
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
return interceptor;
}
/**
* 自定义批量插入 SQL 注入器
*/
@Bean
public InsertBatchSqlInjector insertBatchSqlInjector() {
return new InsertBatchSqlInjector();
}
}
3. 新建MyBaseMapper接口
/**
* MyBaseMapper支持高效批量插入
*/
public interface MyBaseMapper<T> extends BaseMapper<T> {
/**
* 批量插入
*
* @param batchList
* @return
*/
int insertBatchSomeColumn(@Param("list") List<T> batchList);
}
4. 修改UserMapper继承接口
@Repository
public interface UserMapper extends MyBaseMapper<User> {
}
5. 新建测试类UserTest类
@RunWith(SpringRunner.class)
@SpringBootTest(classes = CloudApplication.class)
public class UserTest {
@Autowired
private UserMapper userMapper;
/**
* 批量插入
*/
@Test
public void testBatchSave() {
List<User> users = new ArrayList<>();
User userOne = new User();
userOne.setId(IdUtil.getSnowflakeNextIdStr());
userOne.setName("沈健");
userOne.setUsername("shenjian");
User userTwo = new User();
userTwo.setId(IdUtil.getSnowflakeNextIdStr());
userTwo.setName("算法小生");
userTwo.setUsername("sfxs");
users.add(userOne);
users.add(userTwo);
userMapper.insertBatchSomeColumn(users);
}
}
OK, 批量插入成功
欢迎关注公众号算法小生