动态SQL--Forecah简介

Forecah标签简单介绍

动态SQL–forecah

当要插入的数据是一个数组或集合时,不能写死其中具体有几条数据,此时就需要这个动态SQL标签

示例:

Mapper的Java类:

1
void insertBatch(List<EmpExpr> exprList);

对应的xml映射:

1
2
3
4
5
6
<insert id="insertBatch">
    insert into emp_expr(emp_id, begin, end, company, job)
    values <foreach collection="exprList" item="expr" separator=",">
        (#{expr.empId}, #{expr.begin}, #{expr.end}, #{expr.company}, #{expr.job})
    </foreach>
</insert>

常见属性说明:

1.collection:集合名称

2.item:集合遍历出来的元素/项

3.separator:每一次遍历使用的分隔符(可选)

4.open:遍历开始前拼接的片段(可选)

5.close:遍历结束后拼接的片段(可选)

open属性演示(close同理):

1
2
3
4
5
6
<insert id="insertBatch">
    insert into emp_expr(emp_id, begin, end, company, job)
    <foreach collection="exprList" item="expr" separator="," open="values">
        (#{expr.empId}, #{expr.begin}, #{expr.end}, #{expr.company}, #{expr.job})
    </foreach>
</insert>

此时无论集合内有几条数据都可以正常插入

本站于2025年3月26日建立
使用 Hugo 构建
主题 StackJimmy 设计