mybatis动态查询:<if>和<where>标签的使用

        动态查询时,为了方便直接用的是where 1=1后面跟<if>标签,但是这样有局限,可能会使得我们数据库里设置的索引失效,当数据过多时,导致查询效率下降。用mybatis提供的<where>标签就能规避这样的问题,且<where>标签可判断其是不是第一个查询条件,而选择是否去掉<if>标签包含的sql语句前的and连接。

        话不多说直接上代码:

1.where 1=1 和<if>

        SELECT
		    *
		FROM
		    store_adjust
		WHERE
			1=1
			<if test="id != null and id != ''">
			AND ID = #{id}
			</if>
			<if test="fromWarehouseId != null and fromWarehouseId != ''">
			AND FROM_WAREHOUSE_ID = #{fromWarehouseId}
			</if>
			<if test="toWarehouseId != null and toWarehouseId != ''">
			AND TO_WAREHOUSE_ID = #{toWarehouseId}
			</if>
			<if test="targetType != null and targetType != ''">
			AND TARGET_TYPE = #{targetType}
			</if>
			<if test="startDate != null">
			AND DATE_FORMAT(CREATE_TIME,'%Y%m%d') >= DATE_FORMAT(#{startDate},'%Y%m%d')
			</if>
			<if test="endDate != null">
	        AND DATE_FORMAT(CREATE_TIME,'%Y%m%d') <![CDATA[ <= ]]> 
                DATE_FORMAT(#{endDate},'%Y%m%d')
			</if>
			ORDER BY ID DESC
			<if test="limitBegin != null">
			    limit #{limitBegin},#{pageSize}
			</if>

2. <where>和<if>标签

        SELECT
            *
        FROM
            collection_cost_detail
        <where>
            <if test="collectionBillMainId != null and collectionBillMainId != ''">
              AND collection_bill_main_id = #{collectionBillMainId}
            </if>
            <if test="collectionSubBillType != null and collectionSubBillType != ''">
              AND collection_sub_bill_type = #{collectionSubBillType}
            </if>
            <if test="costType != null and costType != ''">
              AND cost_type = #{costType}
            </if>
        </where>

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值