在项目中,批量操作是常见的需求,尤其是在处理大量数据时,如批量新增商户或批量修改商户信息。直接在java代码中通过循环发送sql到数据库执行是不切实际的,因为这意味着要与数据库建立数万次会话,即使在同一个连接中,也会存在重复编译和执行sql的开销。例如,循环插入10000条数据可能需要3秒钟。
在MyBatis中,支持批量操作,包括批量插入、更新和删除。我们可以直接传入一个List、Set、Map或数组,利用动态SQL标签,MyBatis会自动生成语法正确的SQL语句。
批量插入的语法非常简单,只需在values后面增加插入的值即可。在Mapper文件中,使用foreach标签拼接values部分的语句:

    <insert id="insertBlogList" parametertype="java.util.List">
        insert into blog (bid, name, author_id)
        values
        <foreach collection="list" index="index" item="blogs" separator=",">
            ( #{blogs.bid},#{blogs.name},#{blogs.authorId} )
        </foreach>
    </insert>在Java代码中,直接传入一个List类型的参数:
    /**
     * MyBatis 动态SQL批量插入
     * @throws IOException
     */
    @Test
    public void testInsert() throws IOException {
        long start = System.currentTimeMillis();
        int count = 12000;
        List<Blog> list = new ArrayList<Blog>();
        for (int i=2000; i<count+2000; i++) {
            Blog blog = new Blog();
            blog.setBid(i);
            blog.setName("blog_" + i);
            blog.setAuthorId(i);
            list.add(blog);
        }
        blogMapper.insertBlogList(list);
        long end = System.currentTimeMillis();
        System.out.println("耗时:" + (end - start) + " ms");
    }插入一万条数据大约耗时1秒钟。可以看到,动态SQL批量插入的效率比循环发送SQL执行高得多。关键在于减少了与数据库的交互次数,并且避免了开启和结束事务的时间消耗。
批量更新的语法是通过case when来匹配id相关的字段值。


在Mapper文件中,最关键的是case when和where的配置,需要注意open属性和separator属性。
    <update id="updateBlogList">
        update blog set
        name =
        <foreach close="end" collection="list" index="index" item="blogs" open="case bid" separator=" ">
            when #{blogs.bid} then #{blogs.name}
        </foreach>
        ,author_id =
        <foreach close="end" collection="list" index="index" item="blogs" open="case bid" separator=" ">
            when #{blogs.bid} then #{blogs.authorId}
        </foreach>
        where bid in
        <foreach close=")" collection="list" item="item" open="(" separator=",">
            #{item.bid,jdbcType=INTEGER}
        </foreach>
    </update>在Java代码中,传入一个List类型的参数:
    /**
     * MyBatis 动态SQL批量更新
     * @throws IOException
     */
    @Test
    public void updateBlogList() throws IOException {
        long start = System.currentTimeMillis();
        int count = 12000;
        List<Blog> list = new ArrayList<Blog>();
        for (int i=2000; i<count+2000; i++) {
            Blog blog = new Blog();
            blog.setBid(i);
            blog.setName("updated_blog_" + i);
            blog.setAuthorId(i+100);
            list.add(blog);
        }
        blogMapper.updateBlogList(list);
        long end = System.currentTimeMillis();
        System.out.println("耗时:" + (end - start) + " ms");
    }批量删除的语法与批量更新类似:
    <delete id="deleteByList" parametertype="java.util.List">
        delete from blog where bid in
        <foreach close=")" collection="list" item="item" open="(" separator=",">
            #{item.bid,jdbcType=INTEGER}
        </foreach>
    </delete>在Java代码中,传入一个List类型的参数:
    /**
     * 动态SQL批量删除
     * @throws IOException
     */
    @Test
    public void testDelete() throws IOException {
        SqlSession session = sqlSessionFactory.openSession();
        try {
            BlogMapper mapper = session.getMapper(BlogMapper.class);
            List<Blog> list = new ArrayList<Blog>();
            Blog blog1 = new Blog();
            blog1.setBid(666);
            list.add(blog1);
            Blog blog2 = new Blog();
            blog2.setBid(777);
            list.add(blog2);
            mapper.deleteByList(list);
        } finally {
            session.close();
        }
    }当然,MyBatis的动态标签批量操作也存在一定的缺点。比如数据量特别大时,拼接出来的SQL语句过大。MySQL的服务端对于接收的数据包有大小限制,max_allowed_packet默认是4M,需要修改默认配置或者手动控制条数,才能解决这个问题。
在我们的全局配置文件中,可以配置默认的Executor类型(默认是SIMPLE)。其中有一种BatchExecutor。


一共有三种Executor类型:

三种类型的区别可以通过doUpdate()方法对比:
executeUpdate()是一个语句访问一次数据库,executeBatch()是一批语句访问一次数据库(具体一批发送多少条SQL跟服务端的max_allowed_packet有关)。BatchExecutor底层是对JDBC ps.addBatch()和ps.executeBatch()的封装。
以上就是Mybatis批量操作解析的详细内容,更多请关注php中文网其它相关文章!
 
                        
                        每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
 
                 
                                
                                 收藏
收藏
                                                                             
                                
                                 收藏
收藏
                                                                             
                                
                                 收藏
收藏
                                                                            Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号