批量插入
- xml如下:
<insert id ="batchInsert" parameterType="java.util.List" useGeneratedKeys="true" keyProperty="id">
insert into t_person(name, age, height, weight, update_date) values
<foreach collection="list" item="item" index="index" separator="," >
(
#{item.name},
#{item.age},
#{item.height},
#{item.weight},
now()
)
</foreach>
</insert >
useGeneratedKeys="true"表示自動產生主鍵id,而keyProperty="id"表示主鍵對應的對象屬性為id。
而且主鍵對應的這個Person對象的屬性"id" (也可以是別的命名,比如personId之類的), 最好設置成String類型的,不然可能會出錯。
- Mapper如下:
void batchInsert(List<Person> personList);
這里不使用 @Param注解,那么在xml文件中的collection就默認為 "list"。
- Service如下:
public void batchInsert(List<Person> personList) {
if (CollectionUtils.isNotEmpty(personList)) {
personMapper.batchInsert(personList);
}
}
在批量插入前,需要先做判空處理。
批量更新
- xml如下:
<update id="batchUpdate" parameterType="java.util.List" >
<foreach collection="list" item="item" index="index" open="" close="" separator=";">
update t_person
<set >
<if test="item.name != null" >
fbq_code = #{item.name,jdbcType=VARCHAR},
</if>
<if test="item.age != null" >
dept_code = #{item.age,jdbcType=VARCHAR},
</if>
<if test="item.height != null" >
emp_id = #{item.height,jdbcType=VARCHAR},
</if>
<if test="item.weight != null" >
update_user = #{item.weight,jdbcType=VARCHAR },
</if>
update_date = now()
</set>
where id = #{item.id,jdbcType=INTEGER}
</foreach>
</update>
- Mapper如下:
void batchUpdate(List<Person> personList);
- Service如下:
public void batchUpdate(List<Person> personList) {
if (CollectionUtils.isNotEmpty(personList)) {
personMapper.batchInsert(personList);
}
}