Mybatis-plus 批量插入insertBatchSomeColumn的使用
Mybatis-plus 的 service 层
IService 接口下的 saveBatch 批量插入方法不够高效
Mybatis-plus 的 mapper 层有个选装件
insertBatchSomeColumn
1,新增一个类
此SQL注入器继承了DefaultSqlInjector(默认注入器),调用了DefaultSqlInjector的getMethodList方法
public class MySqlInjector extends DefaultSqlInjector {
@Override
public List<AbstractMethod> getMethodList(Class<?> mapperClass) {
List<AbstractMethod> methodList = super.getMethodList(mapperClass);
methodList.add(new InsertBatchSomeColumn()); //添加批量插入方法
return methodList;
}
}
2,在核心配置类 MybatisPlusConfig 中注入Bean
@Configuration
public class MybatisPlusConfig {
/**
* 其他Bean
*/
// ...
@Bean
public EasySqlInjector sqlInjector() {
return new EasySqlInjector();
}
}
3,在xxxMapper层加一个
返回受影响行数,只测试过MySQL!!!
如果个别字段在 entity 里为 null 但是数据库中有配置默认值, insert 后数据库字段是为 null 而不是默认值!!!
比如,执行语句"alter table test alter column num set default 0"后,如果插入数据"insert into test values (null,"张三",18,null);",num字段的值会是插入的null,而不是我们设置的默认值0。
int insertBatchSomeColumn(List<T> entityList);
4,在类中直接调用,不用写xml文件
List<TXxx> xxxList = 获取xxxList的方法;
//xxxService.saveBatch(xxxList); // 伪批量插入
xxxMapper.insertBatchSomeColumn(xxxList); // 真批量插入