溫馨提示×

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

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

springboot怎么整合mybatis實(shí)現(xiàn)數(shù)據(jù)庫的更新批處理

發(fā)布時(shí)間:2023-03-13 10:15:00 來源:億速云 閱讀:308 作者:iii 欄目:開發(fā)技術(shù)

本文小編為大家詳細(xì)介紹“springboot怎么整合mybatis實(shí)現(xiàn)數(shù)據(jù)庫的更新批處理”,內(nèi)容詳細(xì),步驟清晰,細(xì)節(jié)處理妥當(dāng),希望這篇“springboot怎么整合mybatis實(shí)現(xiàn)數(shù)據(jù)庫的更新批處理”文章能幫助大家解決疑惑,下面跟著小編的思路慢慢深入,一起來學(xué)習(xí)新知識(shí)吧。

    springboot整合mybatis實(shí)現(xiàn)數(shù)據(jù)庫更新批處理

    1.在mapper接口中編寫方法

    /**
     * 修改book表中的銷量和庫存
     * 要使用批處理
     */
    Integer batchBookCountStork(@Param("bookList") List<CartItem> bookList);

    2.在mapper.xml中編寫對(duì)相應(yīng)的更新sql語句

    <update id="batchBookCountStork" parameterType="java.util.List">
        UPDATE t_book
        <set>
            <foreach collection="bookList" item="book" index="index" open="`sales` = CASE `book_id`" close="END,">
                WHEN #{book.bookId} THEN sales+#{book.count}
            </foreach>
            <foreach collection="bookList" item="book" index="index" open="`stock` = CASE `book_id`" close="END,">
                WHEN #{book.bookId} THEN stock-#{book.count}
            </foreach>
        </set>
        <where>
            <foreach collection="bookList" item="book" index="index" open="`book_id` IN(" close=")" separator=",">
                #{book.bookId}
            </foreach>
        </where>
      </update>

    3.這個(gè)配置文件的sql語句流程如下:

    update t_book(表名)
    set sales(這個(gè)是數(shù)據(jù)庫的銷量字段名) = case book_id(這個(gè)是數(shù)據(jù)庫的id字段名)
        when bookid(從list集合中取出來的) then sales+(從集合中取出的數(shù)據(jù))
        ...(這里可以一直進(jìn)行拼接)
      end,
        stock(這個(gè)是數(shù)據(jù)庫的庫存字段名) = CASE book_id(這個(gè)是數(shù)據(jù)庫的id字段名)
        when bookid(從list集合中取出來的) then stock-(從集合中取出數(shù)據(jù))
        ...(這里可以一直進(jìn)行拼接)
      end,
    where `book_id`(這個(gè)是數(shù)據(jù)庫的id字段名) IN(bookid(從list集合中取出來),bookid(從list集合中取出來)...)

    4.這個(gè)sql語句的含義:

    更新表里面的數(shù)據(jù)根據(jù)集合遍歷出來的id值,設(shè)置要更新的字段名,讓要更新的字段值跟這個(gè)表的主鍵id進(jìn)行綁定,當(dāng)這個(gè)主鍵id與list中取出來的id值一致時(shí)就讓這個(gè)要更新的字段名,取then后面的值

    Mybatis批量更新數(shù)據(jù)庫 MybatisBatchUtils batchInsertupdate spring boot

    MybatisBatchUtils

        int cnt = mybatisBatchUtils.batchUpdateOrInsert(addList, UiConfigDetailMapper.class,
                                (item, uiConfigDetailMapper) -> uiConfigDetailMapper.insertSelective(item));
    package cn.XXX.dao.serivce.common;
    
    import com.XXX.doctorusercenter.exception.BusinessException;
    import lombok.extern.slf4j.Slf4j;
    import org.apache.ibatis.session.ExecutorType;
    import org.apache.ibatis.session.SqlSession;
    import org.apache.ibatis.session.SqlSessionFactory;
    import org.springframework.stereotype.Component;
    
    import javax.annotation.Resource;
    import java.util.List;
    import java.util.function.BiFunction;
    
    
    @Slf4j
    @Component
    public class MybatisBatchUtils {
    
        /**
         * 每次處理1000條
         */
        private static final int BATCH_SIZE = 1000;
    
        @Resource
        private SqlSessionFactory sqlSessionFactory;
    
        /**
         * 批量處理修改或者插入
         *
         * @param data        需要被處理的數(shù)據(jù)
         * @param mapperClass Mybatis的Mapper類
         * @param function    自定義處理邏輯
         * @return int 影響的總行數(shù)
         */
        public <T, U, R> int batchUpdateOrInsert(List<T> data, Class<U> mapperClass, BiFunction<T, U, R> function)  {
            int i = 1;
            SqlSession batchSqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH);
            try {
                U mapper = batchSqlSession.getMapper(mapperClass);
                int size = data.size();
                for (T element : data) {
                  function.apply(element, mapper);
                    if ((i % BATCH_SIZE == 0) || i == size) {
                        batchSqlSession.flushStatements();
                    }
                    i++;
                }
                // 非事務(wù)環(huán)境下強(qiáng)制commit,事務(wù)情況下該commit相當(dāng)于無效
                batchSqlSession.commit(true);
            } catch (Exception e) {
                batchSqlSession.rollback();
                // throw new BusinessException(e.getMessage());
                log.error("batchUpdateOrInsert", e);
            } finally {
                batchSqlSession.close();
            }
            return i - 1;
        }
    }

    讀到這里,這篇“springboot怎么整合mybatis實(shí)現(xiàn)數(shù)據(jù)庫的更新批處理”文章已經(jīng)介紹完畢,想要掌握這篇文章的知識(shí)點(diǎn)還需要大家自己動(dòng)手實(shí)踐使用過才能領(lǐng)會(huì),如果想了解更多相關(guān)內(nèi)容的文章,歡迎關(guān)注億速云行業(yè)資訊頻道。

    向AI問一下細(xì)節(jié)

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

    AI