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>

你可能感兴趣的:(mybatis,xml,sql)