mybatis中where标签和trim标签的区别以及使用

1、多个查询条件

在多个查询条件下,由于需要拼接sql语句,所以会在前面加上 where 1 = 1

	<select id="queryList" resultMap="BasBusinessTypeExtendsMap">
	    select
	    <include refid="Base_Column_List"></include>
	    from bas_business_type_setting
	    where 1 = 1
	    <if test="params.dictType != null">
	        and dict_type = #{
    
    params.dictType}
	    </if>
	    <if test="params.libraryType != null">
	        and library_type = #{
    
    params.libraryType}
	    </if>
	</select>

上面1=1的写法虽然可以实现功能,但存在SQL注入的风险,而且可能会造成索引失效全表扫描,因此可以使用where标签代替where 1=1

2、where标签的使用

使用where标签代替where 1=1

    <select id="count" resultType="java.lang.Long">
        select count(1)
        from bas_building
        <where>
            <if test="params.id != null">
                and id = #{
    
    params.id}
            </if>
            <if test="params.idList != null and params.idList.size() > 0 " >
                and id in
                <foreach collection="params.idList" item="idItem" index="index" open="(" close=")" separator=",">
                    #{
    
    idItem}
                </foreach>
            </if>
            <if test="params.buildingNo != null and params.buildingNo != ''">
                and building_no = #{
    
    params.buildingNo}
            </if>
        </where>
    </select>

【作用】
自动去除首个条件中的“AND”或“OR”

注:
1、按照标准写法,第一个if标签内的AND应该不写,但是,就算开发中书写也不会报错。因为where标签会自动的移除了第一个AND链接。但是,第二个之后的if标签内,必须有AND链接。
2、如果没有一个条件符合,则返回所有条目。

3、trim标签的使用

该标签的功能与where类似,并且额外的提供了前缀后缀功能。具体用法如下:

    <select id="count" resultType="java.lang.Long">
        select count(1)
        from bas_building
        <trim prefix="where" prefixOverrides="and|or">
            <if test="params.id != null">
                and id = #{
    
    params.id}
            </if>
            <if test="params.idList != null and params.idList.size() > 0 ">
                and id in
                <foreach collection="params.idList" item="idItem" index="index" open="(" close=")" separator=",">
                    #{
    
    idItem}
                </foreach>
            </if>
            <if test="params.buildingNo != null and params.buildingNo != ''">
                and building_no = #{
    
    params.buildingNo}
            </if>
        </trim>
    </select>

【作用】
1、可以用trim替代where标签。
2、属性 prefix=“where”,表示:加前缀 where。
3、属性 suffix=“)”,表示:加后缀 )。
4、属性 prefixOverrides=“and|or”,前缀覆盖:自动覆盖第一个and或者or。
5、属性 suffixOverrides=“”,后缀覆盖:去掉整个字符串后面多余的字符。

4、trim扩展

trim标签的使用场景比where更多,如下:

<if test="params.businessTypeList != null and params.businessTypeList.size() > 0 ">
    <trim prefix="and ( " prefixOverrides="AND|OR" suffix=" )">
        <foreach collection="params.businessTypeList" item="idItem" index="index">
            OR FIND_IN_SET( #{
    
    idItem}, space_types )
        </foreach>
    </trim>
</if>

在循环的时候拼接多个sql条件,用trim标签的prefixOverrides属性覆盖第一个and或者or,前缀加上"and (“,后缀加上” )",动态生成一个条件满足多种情况的sql。

猜你喜欢

转载自blog.csdn.net/qq_42547733/article/details/129023139