对于 foreach 标签的解释参考了网上的资料,具体如下:
foreach 的主要用在构建in条件中,它可以在SQL语句中进行迭代一个集合。
foreach 元素的属性主要有 item,index,collection,open,separator,close。
- item表示集合中每一个元素进行迭代时的别名,
- index指定一个名字,用于表示在迭代过程中,每次迭代到的位置,
- open表示该语句以什么开始,
- separator表示在每次进行迭代之间以什么符号作为分隔 符,
- close表示以什么结束,
在使用foreach的时候最关键的也是最容易出错的就是collection属性,该属性是必须指定的,但是在不同情况下,该属性的值是不一样的,主要有一下3种情况:
- 如果传入的是单参数且参数类型是一个List的时候,collection属性值为list
- 如果传入的是单参数且参数类型是一个array数组的时候,collection的属性值为array
- 如果传入的参数是多个的时候,我们就需要把它们封装成一个Map了,当然单参数也可以封装成map
一. 批量更新
更新多条记录为多个字段为不同的值
In oracle if you want to execute multiple statements at one time you have to enclose your statements in “begin” and “end” block.
<foreach collection="customerList" item="object" open="begin" close=";end;" separator=";">
UPDATE customer SET isActive = #{object.isactive}
WHERE customerId= #{object.customerId}
</foreach>
更新单个字段【方法一】
<update id="updateByBatch" parameterType="java.util.List">
update t_goods
set NODE_ID=
<foreach collection="list" item="item" index="index" separator=" " open="case" close="end">
when GOODS_ID=#{item.goodsId} then #{item.nodeId}
</foreach>
where GOODS_ID in
<foreach collection="list" index="index" item="item" separator="," open="(" close=")">
#{item.goodsId,jdbcType=BIGINT}
</foreach>
</update>
更新单个字段【方法二】
<update id="updateByBatch" parameterType="java.util.List">
UPDATE t_goods
SET NODE_ID = CASE
foreach collection="list" item="item" index="index">
WHEN GOODS_ID = #{item.goodsId} THEN #{item.nodeId}
</foreach>
END
WHERE GOODS_ID IN
<foreach collection="list" index="index" item="item" open="(" separator="," close=")">
#{item.goodsId}
</foreach>
</update>
更新单个字段【方法三】,上面两种都是简化写法
<update id="updateBatch" parameterType="list">
update course
<trim prefix="set" suffixOverrides=",">
<trim prefix="peopleId =case" suffix="end,">
<foreach collection="list" item="i" index="index">
<if test="i.peopleId!=null">
when id = #{i.id} then #{i.peopleId}
</if>
</foreach>
</trim>
</trim>
where
<foreach collection="list" separator="or" item="i" index="index" >
id = #{i.id}
</foreach>
</update>
更新多个字段
实际上拷贝多次 标签内的内容,并更改 prefix 和 when…then… 的内容即可
<trim prefix="status =case" suffix="end,">
<foreach collection="list" item="item" index="index">
when id=#{item.id} then #{item.status}
</foreach>
</trim>
如果需要为某个字段设置默认值,可以使用 else
<trim prefix="status =case" suffix="end,">
<foreach collection="list" item="item" index="index">
when id=#{item.id} then #{item.status}
</foreach>
else default_value
</trim>
<trim prefix="status =case" suffix="end,">
<foreach collection="list" item="item" index="index">
<if test="item.status !=null and item.status != -1">
when id=#{item.id} then #{item.status}
</if>
</foreach>
else default_value
</trim>
还有更常见的情况就是需要对要更新的数据进行判断,只有符合条件的数据才能进行更新,不满足条件的保持原数据不变,因为mybatis中没有 if…else… 语法,但可以通过多个 if 标签实现同样的效果,如下:
<trim prefix="status =case" suffix="end,">
<foreach collection="list" item="item" index="index">
<if test="item.status !=null and item.status != -1">
when id=#{item.id} then #{item.status}
</if>
<if test="item.status == null or item.status == -1">
when id=#{item.id} then mydata_table.status // 这里就是原数据
</if>
</foreach>
</trim>
UPDATE course
SET name = CASE id
WHEN 1 THEN 'name1'
WHEN 2 THEN 'name2'
WHEN 3 THEN 'name3'
END,
title = CASE id
WHEN 1 THEN 'New Title 1'
WHEN 2 THEN 'New Title 2'
WHEN 3 THEN 'New Title 3'
END
WHERE id IN (1,2,3)
这条sql的意思是,如果id为1,则name的值为name1,title的值为New Title1;依此类推。
在 Mybatis 中的配置则如下:
<update id="updateBatch" parameterType="list">
update course
<trim prefix="set" suffixOverrides=",">
<trim prefix="peopleId =case" suffix="end,">
<foreach collection="list" item="i" index="index">
<if test="i.peopleId!=null">
when id=#{i.id} then #{i.peopleId}
</if>
</foreach>
</trim>
<trim prefix=" roadgridid =case" suffix="end,">
<foreach collection="list" item="i" index="index">
<if test="i.roadgridid!=null">
when id=#{i.id} then #{i.roadgridid}
</if>
</foreach>
</trim>
<trim prefix="type =case" suffix="end," >
<foreach collection="list" item="i" index="index">
<if test="i.type!=null">
when id=#{i.id} then #{i.type}
</if>
</foreach>
</trim>
<trim prefix="unitsid =case" suffix="end," >
<foreach collection="list" item="i" index="index">
<if test="i.unitsid!=null">
when id=#{i.id} then #{i.unitsid}
</if>
</foreach>
</trim>
</trim>
where
<foreach collection="list" separator="or" item="i" index="index" >
id=#{i.id}
</foreach>
</update>
属性说明
1.prefix,suffix 表示在 trim 标签包裹的部分的前面或者后面添加内容
2.如果同时有 prefixOverrides,suffixOverrides 表示会用 prefix,suffix 覆盖 Overrides 中的内容。
3.如果只有 prefixOverrides,suffixOverrides 表示删除开头的或结尾的 xxxOverides 指定的内容。
更新多条记录的同一个字段为同一个值
1. 传map + 传String
NODE_ID从map中取出来,goodsIdList是字符串拼接好的(如下面的"1,2,5")
<update id="deleteByPrimaryKey" parameterType="java.util.Map">
UPDATE t_order_checkout
SET NODE_ID = #{nodeId, jdbcType=VARCHAR}, OPERATOR = #{operator, jdbcType=VARCHAR}
WHERE CHECKOUT_ID IN (${checkoutIdList})
</update>
实际执行脚本
UPDATE t_goods SET NODE_ID = ? WHERE GOODS_ID IN (1,2,5);
2. 传map + 传List
NODE_ID从map中取出来,goodsIdList是用list拼接出来的
<update id="updateByBatchPrimaryKey" parameterType="java.util.Map">
UPDATE t_goods
SET NODE_ID = #{nodeId}
WHERE GOODS_ID IN
<foreach collection="list" index="index" item="item" open="(" separator="," close=")">
#{item.goodsId}
</foreach>
</update>
实际执行脚本
UPDATE t_goods SET NODE_ID = ? WHERE GOODS_ID IN (1,2,5);
二. 批量插入
拼接 sql 方式【不返回 key 】
<insert id="insertList" parameterType="xxx.xxx.PO" useGeneratedKeys="false">
INSERT INTO table_name
(
column_1, column_2, column_3, column_4
)
VALUES
<foreach collection="paramList" item="model" separator=",">
(
#{model.value_1}, #{model.value_2}, #{model.value_3}, #{model.value_4}
)
</foreach>
</insert>
拼接 sql 方式【返回 key 】
<!-- 批量插入生成的兑换码 -->
<insert id ="insertCodeBatch" parameterType="java.util.List" >
<selectKey resultType ="java.lang.Integer" keyProperty= "id" order= "AFTER">
SELECT LAST_INSERT_ID()
</selectKey >
insert into redeem_code
(bach_id, code, type, facevalue,create_user,create_time)
values
<foreach collection ="list" item="reddemCode" index= "index" separator =",">
(
#{reddemCode.batchId},
#{reddemCode.code},
#{reddemCode.type},
#{reddemCode.facevalue},
#{reddemCode.createUser},
#{reddemCode.createTime}
)
</foreach >
</insert >
批处理方式
@SpringBootTest
class DemoApplicationTests {
// @Autowired
// private SqlSessionFactory sqlSessionFactory;
@Autowired
private SqlSessionTemplate sqlSessionTemplate;
@Test
public void testInsertBatch() {
//数据生成
List studentList = createData(100);
//使用批处理
long start = System.currentTimeMillis();
// 新获取一个模式为BATCH,自动提交为false的session
// 如果自动提交设置为true,将无法控制提交的条数,改为最后统一提交,可能导致内存溢出
SqlSession session = sqlSessionTemplate.getSqlSessionFactory().openSession(ExecutorType.BATCH, false);
// SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH, false);
StudentMapper studentMapperNew = sqlSession.getMapper(StudentMapper.class);
studentList.stream().forEach(student -> studentMapperNew.insert(student));
// 这里提交前可以用过计数器来控制每次的提交数量
sqlSession.commit();
sqlSession.clearCache();
System.out.println(System.currentTimeMillis() - start);
}
private List createData(int size) {
List studentList = new ArrayList<>();
Student student;
for (int i = 0; i < size; i++) {
student = new Student();
student.setName("小王" + i);
student.setAge(18);
student.setClassId(1);
student.setPhone("1585xxxx669");
student.setAddress("未知");
studentList.add(student);
}
return studentList;
}
}