溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

MyBatis批量插入的方式有幾種

發(fā)布時間:2021-09-06 18:02:51 來源:億速云 閱讀:230 作者:chen 欄目:編程語言

本篇內(nèi)容主要講解“MyBatis批量插入的方式有幾種”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓小編來帶大家學習“MyBatis批量插入的方式有幾種”吧!

數(shù)據(jù)庫使用的是sqlserver,JDK版本1.8,運行在SpringBoot環(huán)境下,對比3種可用的方式:

  1. 反復執(zhí)行單條插入語句

  2. xml拼接sql

  3. 批處理執(zhí)行

先說結(jié)論:少量插入請使用反復插入單條數(shù)據(jù),方便。數(shù)量較多請使用批處理方式。(可以考慮以有需求的插入數(shù)據(jù)量20條左右為界吧,在我的測試和數(shù)據(jù)庫環(huán)境下耗時都是百毫秒級的,方便最重要)。

無論何時都不用xml拼接sql的方式。

代碼

拼接SQL的xml

newId()是sqlserver生成UUID的函數(shù),與本文內(nèi)容無關(guān)

<insert id="insertByBatch" parameterType="java.util.List">
    INSERT INTO tb_item VALUES
    <foreach collection="list" item="item" index="index" separator=",">
        (newId(),#{item.uniqueCode},#{item.projectId},#{item.name},#{item.type},#{item.packageUnique},
        #{item.isPackage},#{item.factoryId},#{item.projectName},#{item.spec},#{item.length},#{item.weight},
        #{item.material},#{item.setupPosition},#{item.areaPosition},#{item.bottomHeight},#{item.topHeight},
        #{item.serialNumber},#{item.createTime}</foreach>
</insert>

Mapper接口

Mapper是 mybatis插件tk.Mapper 的接口,與本文內(nèi)容關(guān)系不大

public interface ItemMapper extends Mapper<Item> {
    int insertByBatch(List<Item> itemList);
}

Service類

@Service
public class ItemService {
    @Autowired
    private ItemMapper itemMapper;
    @Autowired
    private SqlSessionFactory sqlSessionFactory;
    //批處理
    @Transactional
    public void add(List<Item> itemList) {
        SqlSession session = sqlSessionFactory.openSession(ExecutorType.BATCH,false);
        ItemMapper mapper = session.getMapper(ItemMapper.class);
        for (int i = ; i < itemList.size(); i++) {
            mapper.insertSelective(itemList.get(i));
            if(i%1000==999){//每1000條提交一次防止內(nèi)存溢出
                session.commit();
                session.clearCache();
            }
        }
        session.commit();
        session.clearCache();
    }
    //拼接sql
    @Transactional
    public void add1(List<Item> itemList) {
        itemList.insertByBatch(itemMapper::insertSelective);
    }
    //循環(huán)插入
    @Transactional
    public void add2(List<Item> itemList) {
        itemList.forEach(itemMapper::insertSelective);
    }
}

測試類

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = ApplicationBoot.class)
public class ItemServiceTest {
    @Autowired
    ItemService itemService;

    private List<Item> itemList = new ArrayList<>();
    //生成測試List
    @Before 
    public void createList(){
        String json ="{\n" +
                "        \"areaPosition\": \"TEST\",\n" +
                "        \"bottomHeight\": 5,\n" +
                "        \"factoryId\": \"0\",\n" +
                "        \"length\": 233.233,\n" +
                "        \"material\": \"Q345B\",\n" +
                "        \"name\": \"TEST\",\n" +
                "        \"package\": false,\n" +
                "        \"packageUnique\": \"45f8a0ba0bf048839df85f32ebe5bb81\",\n" +
                "        \"projectId\": \"094b5eb5e0384bb1aaa822880a428b6d\",\n" +
                "        \"projectName\": \"項目_TEST1\",\n" +
                "        \"serialNumber\": \"1/2\",\n" +
                "        \"setupPosition\": \"1B柱\",\n" +
                "        \"spec\": \"200X200X200\",\n" +
                "        \"topHeight\": 10,\n" +
                "        \"type\": \"Steel\",\n" +
                "        \"uniqueCode\": \"12344312\",\n" +
                "        \"weight\": 100\n" +
                "    }";
        Item test1 = JSON.parseObject(json,Item.class);
        test1.setCreateTime(new Date());
        for (int i = ; i < 1000; i++) {//測試會修改此數(shù)量
            itemList.add(test1);
        }
    }
     //批處理
    @Test
    @Transactional
    public void tesInsert() {
        itemService.add(itemList);
    }
    //拼接字符串
    @Test
    @Transactional
    public void testInsert1(){
        itemService.add1(itemList);
    }
    //循環(huán)插入
    @Test
    @Transactional
    public void testInsert2(){
        itemService.add2(itemList);
    }
}

測試結(jié)果:

10條 25條數(shù)據(jù)插入經(jīng)多次測試,波動性較大,但基本都在百毫秒級別

MyBatis批量插入的方式有幾種

其中 拼接sql方式在插入500條和1000條時報錯(似乎是因為sql語句過長,此條跟數(shù)據(jù)庫類型有關(guān),未做其他數(shù)據(jù)庫的測試):com.microsoft.sqlserver.jdbc.SQLServerException: 傳入的表格格式數(shù)據(jù)流(TDS)遠程過程調(diào)用(RPC)協(xié)議流不正確。此 RPC 請求中提供了過多的參數(shù)。最多應為 2100

可以發(fā)現(xiàn)

  • 循環(huán)插入的時間復雜度是 O(n),并且常數(shù)C很大

  • 拼接SQL插入的時間復雜度(應該)是 O(logn),但是成功完成次數(shù)不多,不確定

  • 批處理的效率的時間復雜度是 O(logn),并且常數(shù)C也比較小

結(jié)論

循環(huán)插入單條數(shù)據(jù)雖然效率極低,但是代碼量極少,在使用tk.Mapper的插件情況下,僅需代碼,:

@Transactional
public void add1(List<Item> itemList) {
    itemList.forEach(itemMapper::insertSelective);
}

因此,在需求插入數(shù)據(jù)數(shù)量不多的情況下肯定用它了。

xml拼接sql是最不推薦的方式,使用時有大段的xml和sql語句要寫,很容易出錯,工作效率很低。更關(guān)鍵點是,雖然效率尚可,但是真正需要效率的時候你掛了,要你何用?

批處理執(zhí)行是有大數(shù)據(jù)量插入時推薦的做法,使用起來也比較方便。

到此,相信大家對“MyBatis批量插入的方式有幾種”有了更深的了解,不妨來實際操作一番吧!這里是億速云網(wǎng)站,更多相關(guān)內(nèi)容可以進入相關(guān)頻道進行查詢,關(guān)注我們,繼續(xù)學習!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI