Mybatis动态xml中sql语句拼接参数#和$使用

背景

在开发过程中一些sql语句需要在xml中进行书写,同时需要拼接一些参数,用于动态查询,例如where语句,排序字段动态排序等,涉及到了sql参数和字段注入的情况。

使用#和$

以上两种符号适用于参数占位作用,但是使用有一定的区别。
#用于参数占位,例如字符串、数字型的变量参数占位,where name=#{name} 他在sql中执行语句是 where name=‘*',属于参数变量。
$用于注入参数,一般用于字段名称的注入,例如在排序中使用 order by ${name},不能使用 order by #{name}(因为他等同于 order by '
’)。
代码示例


<select id="getSecDataAnalysisEmsList" resultType="java.util.Map">
        select di.*,cl.categoryname,x,y,z, count(0) over() total from (
        select enterprisename,enterprisecode,sum(watervolume) watervolume,sum(electricityvolume) electricityvolume,sum(gasvolume) gasvolume FROM sec_data_input
        where 1=1
        <if test="region != null and region != ''">
            AND parkname =#{region}
        </if>
        <if test="yearvalue != null and yearvalue != ''">
            AND year =#{yearvalue}
        </if>
        <if test="monthvalue != null and monthvalue != ''">
            AND month =#{monthvalue}
        </if>
        group by enterprisename,enterprisecode
        ) di
        LEFT JOIN eam_enterprise em ON di.enterprisecode = em.enterprisecode
        LEFT JOIN oas_economic_classification ec ON em.industrycode = ec.subclass

        <if test="level == 0">
            left join
            oas_economic_classification cl  on cl.category=ec.category
            where cl.largecategory is null
        </if>
        <if test="level == 1">
            left join
            oas_economic_classification cl  on cl.largecategory=ec.largecategory
            where   ec.category = #{code} and cl.middlecategories is null
        </if>
        <if test="level == 2">
            left join
            oas_economic_classification cl  on cl.middlecategories=ec.middlecategories
            where   ec.largecategory = #{code} and cl.subclass is null
        </if>
        <if test="level == 3">
            left join
            oas_economic_classification cl  on cl.subclass=ec.subclass
            where  ec.middlecategories = #{code}
        </if>
        <if test="level == 4">
            left join
            oas_economic_classification cl  on cl.subclass=ec.subclass
            where  ec.subclass = #{code}
        </if>
        --注入字段名称
        order by  ${orderStr} desc
        --变量替换字段对应的值
        LIMIT #{pageSize} OFFSET #{rowIndex}
    </select>

【腾讯云】11.11云上盛惠,云服务器首年1.8折起,买1年送3个月!境外云服务器15元/月起,买更多省更多!
https://cloud.tencent.com/act/cps/redirect?redirect=5559&cps_key=3e0f3ba5c4cc727403e88457eb5c4914&from=console

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值