成人免费xxxxx在线视频软件_久久精品久久久_亚洲国产精品久久久_天天色天天色_亚洲人成一区_欧美一级欧美三级在线观看

MyBatis批量插入數據優化,那叫一個優雅!

開發 前端
我們使用了 mybatis-plus 框架,并采用其中的 saveBatch 方法進行批量數據插入。然而,通過深入研究源碼,我發現這個方法并沒有如我期望的那樣高效。

在項目開發中,我們經常需要進行大量數據的批量插入操作。然而,在實際應用中,插入大量數據時性能常常成為一個瓶頸。在我最近的項目中,我發現了一些能夠顯著提升批量插入性能的方法,并進行了一系列實驗來驗證它們的有效性。

今日內容介紹,大約花費15分鐘

圖片圖片

背景介紹

我們使用了 mybatis-plus 框架,并采用其中的 saveBatch 方法進行批量數據插入。然而,通過深入研究源碼,我發現這個方法并沒有如我期望的那樣高效

圖片圖片

這是因為最終在執行的時候還是通過for循環一條條執行insert,然后再一批的進行flush ,默認批的消息為1000

圖片圖片

為了找到更優秀的解決方案,我展開了一場性能優化的探索之旅。好了我們現在開始探索

實驗準備

  • 創建一張表tb_student
create table springboot_mp.tb_student
(
    id      bigint auto_increment comment '主鍵ID'
        primary key,
    stuid   varchar(40)   not null comment '學號',
    name    varchar(30)   null comment '姓名',
    age     tinyint       null comment '年齡',
    sex     tinyint(1)    null comment '性別 0 男 1 女',
    dept    varchar(2000) null comment '院系',
    address varchar(400)  null comment '家庭地址',
    constraint stuid
        unique (stuid)
);
  • 創建spring-boot-mybatis-demo項目并在pom.xml中添加依賴

圖片圖片

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
    </dependency>

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.30</version>
    </dependency>


    <dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>mybatis-plus-boot-starter</artifactId>
        <version>3.5.3</version>
    </dependency>


    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
    </dependency>
</dependencies>
  • application.yml配置
server:
  port: 8890

spring:
  application:
    name: mybatis-demo #指定服務名
  datasource:
    username: root
    password: root
#    url: jdbc:mysql://localhost:3306/springboot_mp?useUnicode=true&characterEncoding=utf8&rewriteBatchedStatements=true
    url: jdbc:mysql://localhost:3306/springboot_mp?useUnicode=true&characterEncoding=utf8
    driver-class-name: com.mysql.cj.jdbc.Driver
#
mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
  mapper-locations: classpath*:/mapper/**/*.xml
  • 使用mybatisX生成代碼

圖片圖片

圖片圖片

圖片圖片

探索實驗

每次都是插入100000條數據

注意:因為我的電腦性能比較好,所以才插入這么多數據,大家可以插入1000進行實驗對比

  1. 單條循環插入:傳統方法的基準

首先,我采用了傳統的單條循環插入方法,將每條數據逐一插入數據庫,作為性能對比的基準。

/**
 * @author springboot葵花寶典
 * @description: TODO
 */
@SpringBootTest
public class MybatisTest {

    @Autowired
    private StudentService studentService;

    @Autowired
    private SqlSessionFactory sqlSessionFactory;

    @Test
    public void MybatisBatchSaveOneByOne(){


        SqlSession sqlSession = sqlSessionFactory.openSession();

        try {
            StopWatch stopWatch = new StopWatch();
            stopWatch.start("mybatis plus save one");
            for (int i = 0; i < 100000; i++) {
                Student student = new Student();
                student.setStuid("6840"+i);
                student.setName("zhangsan"+i);

                student.setAge((i%100));


                if(i%2==0){
                    student.setSex(0);
                }else {
                    student.setSex(1);
                }

                student.setDept("計算機學院");
                student.setAddress("廣東省廣州市番禺"+i+"號");
                //一條一條插入
                studentService.save(student);
            }
            sqlSession.commit();
            stopWatch.stop();
            System.out.println("mybatis plus save one:" + stopWatch.getTotalTimeMillis());

        } finally {
            sqlSession.close();
        }

    }

}

發現花費了195569毫秒

圖片圖片

  1. mybatis-plus 的 saveBatch 方法

現在嘗試 mybatis-plus 提供的 saveBatch 方法,期望它能夠提高性能。

@Test
    public void MybatissaveBatch(){


        SqlSession sqlSession = sqlSessionFactory.openSession();

        try {

            List<Student> students = new ArrayList<>();
            StopWatch stopWatch = new StopWatch();

            stopWatch.start("mybatis plus save batch");
            for (int i = 0; i < 100000; i++) {
                Student student = new Student();
                student.setStuid("6840"+i);
                student.setName("zhangsan"+i);

                student.setAge((i%100));


                if(i%2==0){
                    student.setSex(0);
                }else {
                    student.setSex(1);
                }

                student.setDept("計算機學院");
                student.setAddress("廣東省廣州市番禺"+i+"號");
                //一條一條插入
                students.add(student);
            }

            studentService.saveBatch(students);
            sqlSession.commit();
            stopWatch.stop();
            System.out.println("mybatis plus save batch:" + stopWatch.getTotalTimeMillis());

        } finally {
            sqlSession.close();
        }

    }

發現花費9204毫秒,比一條條插入數據性能提高十幾倍

圖片

3.手動拼接 SQL:挑戰傳統的方式

<insert id="saveBatch2">
    insert into springboot_mp.tb_student ( stuid, name, age, sex, dept, address)
    values
    <foreach collection="students" item="stu" index="index" separator=",">
          ( #{stu.stuid}, #{stu.name}, #{stu.age}, #{stu.sex}, #{stu.dept}, #{stu.address})
    </foreach>

</insert>

發現花費10958毫秒,比一條條插入數據性能提高十幾倍,但是和saveBatch性能相差不大

既然都驗證都這了,我就在想,要不要使用JDBC批量插入進行驗證一下,看會不會出現原始的才是最好的結果

4.JDBC 的 executeBatch 方法

嘗試直接使用 JDBC 提供的 executeBatch 方法,看是否有意外的性能提升。

@Test
    public void JDBCSaveBatch() throws SQLException {


        SqlSession sqlSession = sqlSessionFactory.openSession();
        Connection connection = sqlSession.getConnection();
        connection.setAutoCommit(false);



        String sql ="insert into springboot_mp.tb_student ( stuid, name, age, sex, dept, address) values (?, ?, ?, ?, ?, ?);";
        try (PreparedStatement statement = connection.prepareStatement(sql)) {

            List<Student> students = new ArrayList<>();
            StopWatch stopWatch = new StopWatch();
            stopWatch.start("mybatis plus JDBCSaveBatch");
            for (int i = 0; i < 100000; i++) {
                statement.setString(1,"6840"+i);
                statement.setString(2,"zhangsan"+i);
                statement.setInt(3,(i%100));
                if(i%2==0){
                    statement.setInt(4,0);
                }else {
                    statement.setInt(4,1);
                }
                statement.setString(5,"計算機學院");
                statement.setString(6,"廣東省廣州市番禺"+i+"號");


                statement.addBatch();
            }

            statement.executeBatch();
            connection.commit();
            stopWatch.stop();
            System.out.println("mybatis plus JDBCSaveBatch:" + stopWatch.getTotalTimeMillis());

        }
        catch (Exception e){
            System.out.println(e.getMessage());
        }
        finally {

            sqlSession.close();
        }

JDBC executeBatch 的性能會好點,耗費6667毫秒

圖片

但是感覺到這里以后,覺得時候還是比較長,有沒有可以再進行優化的方式,然后我就在ClientPreparedStatement類中發現有一個叫做rewriteBatchedStatements 的屬性,從名字來看是要重寫批操作的 Statement,前面batchHasPlainStatements 已經是 false,取反肯定是 true,所以只要這參數是 true 就會進行一波操作。rewriteBatchedStatements默認是 false。

圖片圖片

圖片

圖片圖片

大家也可以自行網上搜索一下這個神奇的屬性然后我在url添加上這個屬性

圖片圖片

然后繼續跑了下 mybatis-plus 自帶的 saveBatch,果然性能大大提高直接由原來的9204毫秒,提升到現在的3903毫秒

圖片圖片

再來跑一下JDBC 的 executeBatch ,果然也提高了。

直接由原來的6667毫秒,提升到了3794毫秒

圖片

結果對比

批量保存方式

數據量(條)

耗時(ms)

單條循環插入

100000

195569

mybatis-plus saveBatch


100000

9204

mybatis-plus saveBatch(添加 rewrite 參數)

100000

3903

手動拼接 SQL

100000

6667

JDBC executeBatch

100000

10958

JDBC executeBatch(添加 rewrite 參數)

100000

3794

結論

通過實驗結果,我們可以得出以下結論:

  • mybatis-plus 的 saveBatch 方法相比單條循環插入在性能上有所提升,但仍然不夠理想。
  • JDBC 的 executeBatch 方法在默認情況下性能與 mybatis-plus 的 saveBatch 類似,但通過設置 rewriteBatchedStatements 參數為 true 可顯著提高性能。
  • rewriteBatchedStatements 參數的作用是將一批插入拼接成 insert into xxx values (a),(b),(c)... 這樣的一條語句形式,提高了性能。

優化建議

如果您在項目中需要進行批量插入操作,我建議考慮以下優化方案:

  • 如果使用 mybatis-plus,可以嘗試將 JDBC 連接字符串中的 rewriteBatchedStatements 參數設置為 true,以提高 saveBatch 方法的性能。
責任編輯:武曉燕 來源: springboot葵花寶典
相關推薦

2024-11-12 08:20:31

2025-05-30 08:20:54

2025-04-08 08:20:33

2024-10-24 08:21:33

2022-12-12 08:14:47

2025-04-22 08:20:51

2024-12-02 00:59:30

Spring

2025-03-06 08:21:02

判空entity對象

2025-02-28 08:21:00

2025-03-11 08:20:58

2020-11-03 16:00:33

API接口微服務框架編程語言

2021-09-27 07:56:41

MyBatis Plu數據庫批量插入

2025-04-02 12:20:00

開發代碼函數

2022-09-29 10:06:56

SQLMySQL服務端

2021-10-09 06:59:36

技術MyBatis數據

2013-09-22 10:25:23

MySQLSQL性能優化

2020-11-23 10:50:27

MySQLSQL數據庫

2022-06-21 14:44:38

接口數據脫敏

2024-11-07 10:55:26

2024-11-08 15:56:36

點贊
收藏

51CTO技術棧公眾號

主站蜘蛛池模板: 久久狠狠| 国产午夜三级一区二区三 | 亚洲一区二区三区视频 | 手机看片在线播放 | 日本免费一区二区三区四区 | 国产蜜臀97一区二区三区 | 91日韩| 国产精品久久久久久久久久三级 | 欧美色成人 | 蜜桃在线一区二区三区 | 九九综合| 欧美多人在线 | 成人在线视频免费观看 | 成人在线视频看看 | 欧美不卡 | 四虎永久免费地址 | 国内久久 | 天堂久久天堂综合色 | 成人在线黄色 | 韩国av影院 | 亚洲福利| 精品国产99 | 亚洲国产成人久久综合一区,久久久国产99 | 人妖无码 | 免费一区二区三区 | 日韩精品在线看 | 国产精品一区二区三级 | 久久久久久久久久久福利观看 | 国产欧美性成人精品午夜 | 草草影院ccyy | www日本在线 | 成人在线播放网站 | 国产日韩精品在线 | 欧美中国少妇xxx性高请视频 | 久久精品国产亚洲 | 91精品福利 | 男女羞羞视频免费 | 国产高清在线精品 | 精品国产一区二区三区在线观看 | 亚洲综合久久久 | 国内自拍偷拍 |