foreach 可以在 SQL 语句中进行迭代一个集合。foreach元素的属性主要有 item,index,collection,open,separator,close。
假设我们有一个 BatchDTO 的实体类:
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Builder(toBuilder = true)
@AllArgsConstructor
@NoArgsConstructor
@Data
public class BatchDTO {
private String workspaceKey;
private String planId;
private String baselineState;
}
Repository 接口中定义方法:
boolean batchInsert(@Param("list") List<BatchDTO> batchDTOList, @Param("tableName") String tableName);
Mybatis 中 mapper.xml 实现如下:
<insert id="batchInsert" parameterType="java.util.List">
insert into ${tableName} (`workspace_key`, `plan_id`, baseline_state)
values
<foreach collection="list" item="item" separator=",">
(#{item.workspaceKey}, #{item.planId}, #{item.baselineState})
</foreach>
</insert>
Repository 接口中定义方法:
boolean batchUpdate(@Param("planIds") List<BatchDTO> batchDTOList, @Param("tableName") String tableName);
Mybatis 中 mapper.xml 实现如下:
<update id="batchUpdate">
update ${tableName}
set `workspace_key` = "vvv"
where `plan_id` in
<foreach collection="planIds" item="item" index="index" open="(" separator="," close=")">
#{item.planId}
</foreach>
</update>
Repository 接口中定义方法:
List<DAO> batchSelect(@Param("planIds") List<String> planIds, @Param("tableName") String tableName);
Mybatis 中 mapper.xml 实现如下:
<select id="batchSelect" resultMap="DAOMap">
select * from ${tableName}
where 1 = 1
<if test="planIds != null and planIds.size() > 0">
and `plan_id` in
<foreach collection="planIds" open="(" item="planId" close=")" separator=",">
#{planId}
</foreach>
</if>
</select>
如果入参类型是 List 类型,可以直接以字符串类型作为入参,而不用传入一个 List。具体实现如下。
Repository 接口中定义方法:
List<DAO> batchSelect(@Param("planIds") String planIds, @Param("tableName") String tableName);
Mybatis 中 mapper.xml 实现如下:
<select id="batchSelect" resultMap="PlanBaselineStateDAOMap">
select * from ${tableName}
where 1 = 1
<if test="planIds != null and planIds != ''">
and `plan_id` in
<foreach collection="planIds.split(',')" open="(" item="planId" close=")" separator=",">
#{planId}
</foreach>
</if>
</select>
这里举例使用 foreach 遍历 map。使用 foreach 遍历 map 时,foreach 标签中的参数 index 表示的就是 map 的 key,item 就是 map 的 Value。
Repository 接口中定义方法:
boolean batchInsert(@Param("batchInsertMap") Map<String, String> batchInsertMap, @Param("tableName") String tableName);
Mybatis 中 mapper.xml 实现如下:
<insert id="batchInsert" parameterType="java.util.Map">
insert into ${tableName} (`workspace_key`, `plan_id`)
values
<foreach collection="batchInsertMap" index="key" item="value" separator=",">
(#{key}, #{value})
</foreach>
</insert>