MyBatis 利用foreach处理数组参数传入

本文介绍了如何使用MyBatis的foreach标签处理数组参数,生成如'BUSINESS_CUSTOMER in ('AMAZON', 'BAIDU')'这样的SQL片段,应用于多条件查询。" 118190663,10500202,Apache ECharts 中的旭日图(Sunburst)详解,"['数据可视化', 'ECharts', '旭日图']

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. 使用IN实现多条件查询,传入的参数是String数组,如 issuePriority = ["ABC","BCD","EFG"]
2. 在MyBatis xml文件中,使用foreach,其中,需要使用$ 而不是#, {item}需要用单引号括起来,如'${item}'
<if test="issuePriority != null and issuePriority.length > 0 "> 
    and ISSUE_PRIORITY in <foreach collection="issuePriority" item="item" index="index" open="(" close=")" separator=","> 
'${item}'
 </foreach> </if>

<!-- 根據查詢條件,查詢需求信息 -->
<select id="getDailyWorkingIssueListWithArrayParameters" resultMap="DailyWorkingIssue">
    SELECT *
    FROM MES_KPI_ISSUE_T
    WHERE 1=1
    <if test="issueId != null and issueId != ''">
        and ISSUE_ID = #{issueId}
    </if>
    <if test="issueSubject != null and issueSubject != ''">
        and ISSUE_SUBJECT = #{issueSubject}
    </if>
    <if test="issuePriority != null and issuePriority.length > 0 ">
        and ISSUE_PRIORITY in
            <foreach collection="issuePriority" item="item" index="index" open="(" close=")" separator=",">
                '${item}'
            </foreach>
    </if>
    <if test="beginDate != null ">
        AND date_format(BEGIN_DATE,'%Y-%m-%d') &gt;= date_format(#{beginDate},'%Y-%m-%d')
    </if>
    <if test="endDate != null ">
        AND date_format(BEGIN_DATE,'%Y-%m-%d') &lt;= date_format(#{endDate},'%Y-%m-%d')
    </if>
</select>

 

最后生成的SQL语句

SELECT * FROM MES_KPI_ISSUE_T WHERE 1=1 and BUSINESS_LEVEL in ( 'L6' ) and BUSINESS_CUSTOMER in ( 'AMAZON' , 'BAIDU' ) 

SELECT * FROM MES_KPI_ISSUE_T  WHERE 1=1 and ISSUE_PRIORITY in ( 'A' ) 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值