最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Mybatis批量插入的三種實(shí)現(xiàn)方法

 更新時(shí)間:2023年10月30日 09:23:58   作者:秋官  
在日常開發(fā)中,如果要操作數(shù)據(jù)庫(kù)的話,或多或少都會(huì)遇到批量數(shù)據(jù)的處理,本文主要介紹了Mybatis批量插入的三種實(shí)現(xiàn)方法,感興趣的可以了解一下

在日常開發(fā)中,如果要操作數(shù)據(jù)庫(kù)的話,或多或少都會(huì)遇到批量數(shù)據(jù)的處理,我們公司使用的mybaits-plus作為持久層的框架,今天就簡(jiǎn)單介紹一下mybaits批量操作數(shù)據(jù)庫(kù)的幾種方式。

1.循環(huán)插入

其實(shí)這種方式并不是批量插入,只是在日常開發(fā)中,使用這種方式的還是比較多的。

@RunWith(SpringRunner.class)
@SpringBootTest
public class BatchTest {

    @Resource
    private StudentMapper studentMapper;


    @Test
    public void test(){
        List<Student> students = generateStudentData(100);

        long start = System.currentTimeMillis();
        students.forEach(studentMapper::insert);
        System.out.println("循環(huán)插入: " + students.size() + " 條數(shù)據(jù),共計(jì)耗時(shí):" + (System.currentTimeMillis() - start) + " 毫秒");
    }


    public static List<Student> generateStudentData(int size){
        List<Student> list = new ArrayList<>(size);
        Random random = new Random();
        for (int i = 0; i < size; i++) {
            Student student = new Student();
            student.setName("zhangsan-" + i);
            student.setAge(random.nextInt(40));
            student.setPhone("15077828899");
            student.setBirthday(LocalDateTime.now());

            list.add(student);
        }

        return list;
    }
}

2.foreach方式插入

@RunWith(SpringRunner.class)
@SpringBootTest
public class BatchTest {

    @Resource
    private StudentMapper studentMapper;


    @Test
    public void test3(){
        List<Student> students = generateStudentData(100);

        long foreachStart = System.currentTimeMillis();
        studentMapper.insertBatch(students);
        System.out.println("foreach插入: " + students.size() + " 條數(shù)據(jù),共計(jì)耗時(shí):" + (System.currentTimeMillis() - foreachStart) + " 毫秒");
    }


    public static List<Student> generateStudentData(int size){
        List<Student> list = new ArrayList<>(size);
        Random random = new Random();
        for (int i = 0; i < size; i++) {
            Student student = new Student();
            student.setName("zhangsan-" + i);
            student.setAge(random.nextInt(40));
            student.setPhone("15077828899");
            student.setBirthday(LocalDateTime.now());

            list.add(student);
        }

        return list;
    }
}

StudentMapper 接口如下:

public interface StudentMapper extends BaseMapper<Student> {

    /**
     * 批量插入
     */
    int insertBatch(@Param("entities") List<Student> entities);

    /**
     * 批量更新或者插入
     */
    int insertOrUpdateBatch(@Param("entities") List<Student> entities);

}

StudentMapper.xml內(nèi)容如下:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.efreight.oss.transfer.dao.StudentMapper">

    <resultMap type="com.efreight.oss.transfer.entity.Student" id="StudentMap">
        <result property="id" column="id" jdbcType="INTEGER"/>
        <result property="name" column="name" jdbcType="VARCHAR"/>
        <result property="age" column="age" jdbcType="INTEGER"/>
        <result property="birthday" column="birthday" jdbcType="TIMESTAMP"/>
        <result property="phone" column="phone" jdbcType="VARCHAR"/>
    </resultMap>

    <!-- 批量插入 -->
    <insert id="insertBatch" keyProperty="id" useGeneratedKeys="true">
        insert into cargo.student(name, age, birthday, phone)
        values
        <foreach collection="entities" item="entity" separator=",">
        (#{entity.name}, #{entity.age}, #{entity.birthday}, #{entity.phone})
        </foreach>
    </insert>

    <!-- 批量插入或按主鍵更新 -->
    <insert id="insertOrUpdateBatch" keyProperty="id" useGeneratedKeys="true">
        insert into cargo.student(name, age, birthday, phone)
        values
        <foreach collection="entities" item="entity" separator=",">
            (#{entity.name}, #{entity.age}, #{entity.birthday}, #{entity.phone})
        </foreach>
        on duplicate key update
        name = values(name) , age = values(age) , birthday = values(birthday) , phone = values(phone)
    </insert>

</mapper>

搭配 useGeneratedKeys="true" 和 keyProperty="id" 屬性(這個(gè)id是javaBean的屬性),可以獲取自增主鍵,有時(shí)候這個(gè)主鍵我們是非常需要的。

3.批處理方式插入

通過 ExecutorType.BATCH來構(gòu)建一個(gè)可以完成批處理工作的執(zhí)行器

@RunWith(SpringRunner.class)
@SpringBootTest
public class BatchTest {

    @Resource
    private StudentMapper studentMapper;

    @Resource
    private SqlSessionTemplate sqlSessionTemplate;


    @Test
    public void test2(){
        List<Student> students = generateStudentData(100);

        long batchStart = System.currentTimeMillis();
        try(SqlSession sqlSession = this.sqlSessionTemplate.getSqlSessionFactory().openSession(ExecutorType.BATCH, false)) {
            StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
            for (int i = 0; i < students.size(); i++) {  
                studentMapper.insert(students.get(i));  
                if (i % 1000 == 0 || i == students.size() - 1) {  
                sqlSession.flushStatements();  
                }  
            }  
            sqlSession.commit();
        }
        System.out.println("mybatis批處理插入: " + students.size() + " 條數(shù)據(jù),共計(jì)耗時(shí):" + (System.currentTimeMillis() - batchStart) + " 毫秒");
    }


    public static List<Student> generateStudentData(int size){
        List<Student> list = new ArrayList<>(size);
        Random random = new Random();
        for (int i = 0; i < size; i++) {
            Student student = new Student();
            student.setName("zhangsan-" + i);
            student.setAge(random.nextInt(40));
            student.setPhone("15077828899");
            student.setBirthday(LocalDateTime.now());

            list.add(student);
        }

        return list;
    }
}

注意:批處理方式是無法獲取自增主鍵的。

順便說一下,現(xiàn)在使用mybatis-plus的也非常多,他也提供了批量插入的功能,它內(nèi)部使用的就是ExecutorType.BATCH 來構(gòu)建的。

關(guān)于三者性能的比較大家可以跑下看看,循環(huán)插入的方式性能最差,能不用就盡量不用,在foreach和批處理中,我測(cè)試發(fā)現(xiàn)foreach的性能最好(我用的MySQL是5.7),所以項(xiàng)目中我們批處理使用的都是foreach, 因?yàn)橐话阄覀円话闩坎迦胱疃嘁簿?000條左右的數(shù)據(jù),但是大家可以根據(jù)自己機(jī)器的實(shí)際情況,去跑一下看看。

插入方式100條1000條10000條10萬條
循環(huán)插入1599 毫秒14336 毫秒140793 毫秒*
foreach62 毫秒364 毫秒3249 毫秒23940 毫秒
批處理321 毫秒6868 毫秒72851 毫秒457005 毫秒

到此這篇關(guān)于Mybatis批量插入的三種實(shí)現(xiàn)方法的文章就介紹到這了,更多相關(guān)Mybatis批量插入 內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • 基于Springboot2.0構(gòu)建ES的多客戶端

    基于Springboot2.0構(gòu)建ES的多客戶端

    這篇文章主要為大家詳細(xì)介紹了基于Springboot2.0構(gòu)建ES的多客戶端,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2019-04-04
  • spring-boot整合dubbo:Spring-boot-dubbo-starter

    spring-boot整合dubbo:Spring-boot-dubbo-starter

    這篇文章主要介紹了spring-boot整合dubbo:Spring-boot-dubbo-starter的相關(guān)資料,非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友可以參考下
    2017-05-05
  • java字符串比較獲取字符串出現(xiàn)次數(shù)的示例

    java字符串比較獲取字符串出現(xiàn)次數(shù)的示例

    java獲取一個(gè)字符串在整個(gè)字符串出現(xiàn)的次數(shù),下面寫出我的思路和二個(gè)實(shí)現(xiàn)方法,大家參考使用吧
    2014-01-01
  • mybatis主表與明細(xì)表一對(duì)多的同時(shí)插入操作方法

    mybatis主表與明細(xì)表一對(duì)多的同時(shí)插入操作方法

    對(duì)主表(采購(gòu)申請(qǐng)表)和明細(xì)表(申請(qǐng)物資表)同時(shí)進(jìn)行插入操作insert,怎么實(shí)現(xiàn)呢,下面給大家分享mybatis主表與明細(xì)表一對(duì)多的同時(shí)插入操作方法,感興趣的朋友一起看看吧
    2023-02-02
  • Java中的升序和降序問題

    Java中的升序和降序問題

    這篇文章主要介紹了Java中的升序和降序問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-11-11
  • 詳解SpringBoot初始教程之Tomcat、Https配置以及Jetty優(yōu)化

    詳解SpringBoot初始教程之Tomcat、Https配置以及Jetty優(yōu)化

    本篇文章主要介紹了詳解SpringBoot初始教程之Tomcat、Https配置以及Jetty優(yōu)化,具有一定的參考價(jià)值,有興趣的可以了解一下
    2017-09-09
  • springboot 如何使用jackson來處理實(shí)體類

    springboot 如何使用jackson來處理實(shí)體類

    這篇文章主要介紹了springboot使用jackson來處理實(shí)體類的操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-10-10
  • 淺談SpringMVC國(guó)際化支持

    淺談SpringMVC國(guó)際化支持

    這篇文章主要介紹了淺談SpringMVC國(guó)際化支持,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2018-03-03
  • 帶你了解Java Maven的打包操作

    帶你了解Java Maven的打包操作

    這篇文章主要介紹了Maven打包的相關(guān)知識(shí),本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2021-09-09
  • Spring Boot配置接口WebMvcConfigurer的實(shí)現(xiàn)

    Spring Boot配置接口WebMvcConfigurer的實(shí)現(xiàn)

    這篇文章主要介紹了SpringBoot配置接口WebMvcConfigurer的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-11-11

最新評(píng)論

紫阳县| 南乐县| 武清区| 宝山区| 项城市| 平远县| 襄樊市| 奉贤区| 六安市| 驻马店市| 新营市| 思茅市| 石棉县| 高青县| 朝阳市| 青海省| 玉林市| 江华| 蛟河市| 漯河市| 礼泉县| 手游| 江山市| 夏津县| 田东县| 华坪县| 扶风县| 文山县| 象州县| 靖西县| 梓潼县| 辰溪县| 商河县| 凤城市| 和硕县| 渝中区| 西充县| 嘉祥县| 全州县| 清流县| 连山|