mysql存储过程实例详解 mysql批量insert数据上限
2021-11-09 03:33:42 爱问问
文章目录
- 前言
- 1.单条数据插入表:
- 1.1mapper代码:
- 1.2单元测试:
- 2.多条数据插入表:
- 2.1方法1:
- 2.2方法2:
- 2.3单元测试:
- 1.单条数据插入表:
- 结尾
前言
Mybatis批量插入返回自增ID这在很多场景下会用到,比方说请求过来以后返回结果后的回更用自增id处理,或者主表产生id后去做其他的子表的业务关联。
1.单条数据插入表:
1.1mapper代码:
重点是配置:
useGeneratedKeys=“true” keyProperty=“id”
<insert id="insertSelective" parameterType="com.gaosi.user.gaosiuserjack.modle.UserLocal" useGeneratedKeys="true" keyProperty="id" >
insert into tb_user_local
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="id != null">
id,
</if>
<if test="name != null">
name,
</if>
<if test="age != null">
age,
</if>
<if test="createTime != null">
create_time,
</if>
<if test="updateTime != null">
update_time,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="id != null">
#{id,jdbcType=INTEGER},
</if>
<if test="name != null">
#{name,jdbcType=VARCHAR},
</if>
<if test="age != null">
#{age,jdbcType=INTEGER},
</if>
<if test="createTime != null">
#{createTime,jdbcType=TIMESTAMP},
</if>
<if test="updateTime != null">
#{updateTime,jdbcType=TIMESTAMP},
</if>
</trim>
</insert>
1.2单元测试:
@Test
public void insert1(){
UserLocal userLocal=new UserLocal();
userLocal.setName("单个姓名");
int result=userLocalMapper.insertSelective(userLocal);
System.out.println(userLocal);
}
2.多条数据插入表:
2.1方法1:
<insert id="insertBatch2" parameterType="java.util.List" useGeneratedKeys="true" keyProperty="id">
insert into tb_user_local (name,create_time)
<foreach collection="list" item="item" index="index" separator="union all">
SELECT
#{item.name},
now()
FROM DUAL
</foreach>
</insert>
2.2方法2:
<insert id="insertBatch" parameterType="java.util.List" useGeneratedKeys="true" keyProperty="id">
INSERT INTO
tb_user_local (name,create_time)
VALUES
<foreach collection="list" item="item" index="index" separator=",">
(#{item.name},now())
</foreach>
</insert>
2.3单元测试:
@Test
public void insertBatch(){
List<UserLocal>list=new ArrayList<>();
for (int i=0;i<3;i++){
UserLocal userLocal=new UserLocal();
userLocal.setName(i+"姓名");
list.add(userLocal);
}
int result=userLocalMapper.insertBatch2(list);
System.out.println(list);
}
结尾
这其中需要注意的就是mybatis的版本必须是3.3x以上的版本,不能使用ON DUPLICATE KEY UPDATE等语法,如果使用的话,多条的数据只会返回第一条的数据自增id。这就是我使用mybatis批量插入后的总结,非常的实用,希望能帮助到大家。
声明:此文信息来源于网络,登载此文只为提供信息参考,并不用于任何商业目的。如有侵权,请及时联系我们:baisebaisebaise@yeah.net