首页 > 文章列表 > springboot怎么整合mybatis实现数据库的更新批处理

springboot怎么整合mybatis实现数据库的更新批处理

mybatis 数据库 springboot
130 2023-05-10

    springboot整合mybatis实现数据库更新批处理

    1.在mapper接口中编写方法

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

    2.在mapper.xml中编写对相应的更新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.这个配置文件的sql语句流程如下:

    update t_book(表名)
    set sales(这个是数据库的销量字段名) = case book_id(这个是数据库的id字段名)
        when bookid(从list集合中取出来的) then sales+(从集合中取出的数据)
        ...(这里可以一直进行拼接)
      end,
        stock(这个是数据库的库存字段名) = CASE book_id(这个是数据库的id字段名)
        when bookid(从list集合中取出来的) then stock-(从集合中取出数据)
        ...(这里可以一直进行拼接)
      end,
    where `book_id`(这个是数据库的id字段名) IN(bookid(从list集合中取出来),bookid(从list集合中取出来)...)

    4.这个sql语句的含义:

    更新表里面的数据根据集合遍历出来的id值,设置要更新的字段名,让要更新的字段值跟这个表的主键id进行绑定,当这个主键id与list中取出来的id值一致时就让这个要更新的字段名,取then后面的值

    Mybatis批量更新数据库 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        需要被处理的数据
         * @param mapperClass Mybatis的Mapper类
         * @param function    自定义处理逻辑
         * @return int 影响的总行数
         */
        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++;
                }
                // 非事务环境下强制commit,事务情况下该commit相当于无效
                batchSqlSession.commit(true);
            } catch (Exception e) {
                batchSqlSession.rollback();
                // throw new BusinessException(e.getMessage());
                log.error("batchUpdateOrInsert", e);
            } finally {
                batchSqlSession.close();
            }
            return i - 1;
        }
    }