前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Mybatis 批量插入数据 SQL

Mybatis 批量插入数据 SQL

作者头像
一个会写诗的程序员
发布2019-11-12 14:08:34
4K0
发布2019-11-12 14:08:34
举报

批量插入时,xxxMapper.java 中方法的参数都必须是 List ,泛型可以是 bean ,也可以是 Map 。配合使用 mybatis 的 foreach 即可。示例如下:

DemoMapper.java

public Integer batchInsertDemo(List<Demo> list);

1、只批量插入数值 这种写法适合插入数据的项不变,即 sql 中 VALUES 前括号中的列不变。若插入的项有所变化则适用下一种方法。 DemoMapper.xml

<insert id="batchInsertDemo" parameterType="java.util.List" >
    INSERT INTO demo(id,name,code,age,address) 
    VALUES 
    <foreach collection="list" item="item" index="index" separator="," >  
        (#{item.id},#{item.name},#{item.code},#{item.age},#{item.address}) 
    </foreach> 
</insert>

2、根据数值变动插入选项 此时需适用 foreach 循环包含整个sql语句,VALUES 前后括号中的插入项和插入数据使用 trim 标签,再配合使用 if 标签即可。示例如下:

<insert id="batchInsertDemo" parameterType="list" >
        <foreach collection="list" item="item" index="index" separator=";">
            INSERT INTO demo
            <trim prefix="(" suffix=")" suffixOverrides="," >
                <if test="item.id!= null">
                    id,
                </if>
                <if test="item.name!= null">
                    name,
                </if>
                <if test="item.code != null">
                    code,
                </if>
                <if test="item.age!= null">
                    age,
                </if>
                <if test="item.address!= null">
                    address,
                </if>
            </trim>
            <trim prefix="values (" suffix=")" suffixOverrides="," >
                if test="item.id!= null">
                    #{item.id,jdbcType=INTEGER},
                </if>
                <if test="item.name!= null">
                    #{item.name,jdbcType=VARCHAR},
                </if>
                <if test="item.code != null">
                    #{item.code ,jdbcType=VARCHAR},
                </if>
               <if test="item.age!= null">
                    #{item.age,jdbcType=INTEGER},
                </if>
                <if test="item.address!= null">
                    #{item.address,jdbcType=VARCHAR},
                </if>
            </trim>
        </foreach>
    </insert>

注意事项

特别注意:mysql默认接受sql的大小是1048576(1M),即第三种方式若数据量超过1M会报如下异常:(可通过调整MySQL安装目录下的my.ini文件中[mysqld]段的"max_allowed_packet = 1M")

nested exception is com.mysql.jdbc.PacketTooBigException: Packet for query is too large (5677854 > 1048576).
You can change this value on the server by setting the max_allowed_packet' variable.
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
云数据库 SQL Server
腾讯云数据库 SQL Server (TencentDB for SQL Server)是业界最常用的商用数据库之一,对基于 Windows 架构的应用程序具有完美的支持。TencentDB for SQL Server 拥有微软正版授权,可持续为用户提供最新的功能,避免未授权使用软件的风险。具有即开即用、稳定可靠、安全运行、弹性扩缩等特点。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档