5. SpringBoot3+MybatisPlusをベースに一括挿入を実装する

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、バッチ挿入が成功しました

ニッチなパブリック アカウント アルゴリズムのフォローへようこそ

おすすめ

転載: blog.csdn.net/SJshenjian/article/details/133783843