1.自定义SqlInjector继承DefaultSqlInjector,重写getMethodList方法,在里面添加批量插入的方法。methodList.add(new InsertBatchSomeColumn());
public class MySqlInjector extends DefaultSqlInjector {
@Override
public List<AbstractMethod> getMethodList(Class<?> mapperClass, TableInfo tableInfo) {
List<AbstractMethod> methodList = super.getMethodList(mapperClass,tableInfo);
//添加批量插入方法
methodList.add(new InsertBatchSomeColumn());
return methodList;
}
}
2.将bean注入spring容器中
@Configuration
public class MybatisPlusConfig {
@Bean
@Primary
public MySqlInjector mySqlInjector() {
return new MySqlInjector();
}
}
3.dao继承BaseMapper,在里面添加insertBatchSomeColumn()方法,注意这个方法名需要和之前添加的methodList.add(new InsertBatchSomeColumn());里的InsertBatchSomeColumn相同。
public interface DeviceDao extends BaseMapper<Device> {
/**
* 批量插入 仅适用于mysql
*
*/
Integer insertBatchSomeColumn(Collection<Device> devices);
}
4.最后在数据源url后面添加rewriteBatchedStatements=true,这样就实现了正真的批量插入,效率非常的高
rewriteBatchedStatements=true