项目中,尽量使用批量插入,减少数据库磁盘IO的操作,提高效率
注意事项:
1 MybatisPlus3.5版本和3.3版本有些许不同,3.3版本会少一个tableInfo参数,创建EasySqlInjector类
package com.lanran.transactional.config;
import com.baomidou.mybatisplus.core.injector.AbstractMethod;
import com.baomidou.mybatisplus.core.injector.DefaultSqlInjector;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.baomidou.mybatisplus.extension.injector.methods.InsertBatchSomeColumn;
import java.util.List;
/**
* @Author suolong
* @Date 2022/7/21 9:59
* @Version 2.0
*/
public class EasySqlInjector extends DefaultSqlInjector {
@Override
public List<AbstractMethod> getMethodList(Class<?> mapperClass, TableInfo tableInfo) {
// TODO Auto-generated method stub
List<AbstractMethod> methodList = super.getMethodList(mapperClass, tableInfo);
methodList.add(new InsertBatchSomeColumn()); // 添加InsertBatchSomeColumn方法
return methodList;
}
}
2 添加mybatisplus配置类
package com.lanran.transactional.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @Author suolong
* @Date 2022/7/21 9:57
* @Version 2.0
*/
@Configuration
public class MybatisPlusConfig {
@Bean
public EasySqlInjector easySqlInjector () {
return new EasySqlInjector();
}
}
3 启动类,一定要添加MapperScan
package com.lanran.transactional;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@MapperScan("com.lanran.transactional.dao")
@SpringBootApplication
public class TransactionalApplication {
public static void main(String[] args) {
SpringApplication.run(TransactionalApplication.class, args);
}
}
4 mapper、xml、entity都是使用mybatisplus生成的,测试类如下
package com.lanran.transactional;
import com.lanran.transactional.dao.JpaTestMapper;
import com.lanran.transactional.dao.PaymentMapper;
import com.lanran.transactional.entity.Payment;
import com.lanran.transactional.service.PaymentService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.ArrayList;
import java.util.List;
@SpringBootTest
class TransactionalApplicationTests {
@Test
void contextLoads() {
}
@Autowired
PaymentMapper paymentMapper;
@Test
public void batchInsertTest(){
List<Payment> payments = new ArrayList<>();
for (int i = 0; i < 5; i++) {
Payment p = new Payment();
p.setSerial(String.valueOf(i));
payments.add(p);
}
Integer integer = paymentMapper.insertBatchSomeColumn(payments);
System.out.println(integer);
}
}
5 application配置文件
spring:
datasource:
type: com.zaxxer.hikari.HikariDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/mysqltest?characterEncoding=utf-8&useSSL=false
username: root
password: 123456
sql:
init:
encoding: utf-8
6 测试结果,一共批量插入了5条数据
7 整体项目目录
自己也可以在xml中写sql语句,只是表太多有点麻烦
作为程序员第 213 篇文章,每次写一句歌词记录一下,看看人生有几首歌的时间,wahahaha …