前言
当我们要实现一次性插入很多条数据的时候,这时候普通的for循环添加,性能就有点低了,就要用到批量插入了,排量插入的方法很多,接下来我就描述最常用的,而且不是特别大的量的时候,性能还是可以的。
一、批量新增
1.xml中怎么写
<insert id="insertByBatch" parameterType="java.util.List" useGeneratedKeys="true" keyProperty="id">
insert into usm_game_characters (aid, create_date, operation_date,
create_user, operation_user, del_flag,
person_name, gender, person_description,
person_location, sort)
values
<if test="list != null">
<foreach collection="list" item="item" index="index" separator=",">
(#{item.aid,jdbcType=VARCHAR}, #{item.createDate,jdbcType=TIMESTAMP}, #{item.operationDate,jdbcType=TIMESTAMP},
#{item.createUser,jdbcType=VARCHAR}, #{item.operationUser,jdbcType=VARCHAR}, #{item.DelFlagEnum,jdbcType=TINYINT},
#{item.personName,jdbcType=VARCHAR}, #{item.GenderEnum,jdbcType=TINYINT}, #{item.personDescription,jdbcType=VARCHAR},
#{item.personLocation,jdbcType=VARCHAR}, #{item.sort,jdbcType=INTEGER})
</foreach>
</if>
</insert>
2.mapper中怎么传参数
int insertByBatch(List<Person> persons);
二、批量修改
1.xml中怎么写
<update id="updateByBatch" parameterType="java.util.List">
<foreach collection="list" item="item" index="index" separator=";">
update cnpc_order_excel
<set>
<if test="item.aid != null">
aid = #{item.aid,jdbcType=VARCHAR},
</if>
<if test="item.createDate != null">
create_date = #{item.createDate,jdbcType=TIMESTAMP},
</if>
<if test="item.operationDate != null">
operation_date = #{item.operationDate,jdbcType=TIMESTAMP},
</if>
<if test="item.createUser != null">
create_user = #{item.createUser,jdbcType=VARCHAR},
</if>
<if test="item.operationUser != null">
operation_user = #{item.operationUser,jdbcType=VARCHAR},
</if>
<if test="item.DelFlagEnum != null">
del_flag = #{item.DelFlagEnum,jdbcType=TINYINT},
</if>
<if test="item.personName != null">
person_name = #{item.personName,jdbcType=VARCHAR},
</if>
<if test="item.GenderEnum != null">
gender = #{item.GenderEnum,jdbcType=TINYINT},
</if>
<if test="item.personDescription != null">
person_description = #{item.personDescription,jdbcType=VARCHAR},
</if>
<if test="item.personLocation != null">
person_location = #{item.personLocation,jdbcType=VARCHAR},
</if>
<if test="item.sort != null">
sort = #{item.sort,jdbcType=INTEGER},
</if>
</set>
where id = #{item.id,jdbcType=BIGINT}
</foreach>
</update>
2.mapper中怎么传参数
int updateByBatch(List<Person> persons);
三、相关参数解释
大标签参数
1.parameterType:表示传入的参数类型,这里是一个 java.util.List 类型的数据,即需要插入的数据列表。
2.useGeneratedKeys:表示是否使用自动生成的主键,这里设置为 true,即会生成自增的主键值。
3.keyProperty:表示生成的主键值将被设置到哪个属性中,这里是 id 属性。
foreach 标签参数:
1.collection:表示要遍历的集合,这里是一个名为 “list” 的集合。
2.item:表示集合中的每个元素在遍历过程中的名称"。
3.index:表示集合元素在遍历过程中的索引,即元素在集合中的位置。
4.separator:表示每个遍历生成的 SQL 语句片段之间的分隔符。
总结
首先欢迎大家观看,小白选手要是在开发中遇到什么问题,可以像我留言,我知道的保证知无不言。