where 1=1 这个条件始终为True,在不定数量查询条件情况下,1=1可以很方便的规范语句。
主要体现在mybatis的.xml查询语句中
<select id="countByQuery" parameterType="com.mtoliv.XXX" resultMap="BaseResultMap">
select count(*) count_sum from v_alert_device where 1=1
<if test="customerId != null">
and customer_id = #{customerId,jdbcType=VARCHAR}
</if>
<if test="alertTypeId != null">
and alert_type_id = #{alertTypeId,jdbcType=INTEGER}
</if>
order by count_sum desc LIMIT 10
</select>①加了where 1=1,并且假设customerId和alertTypeId有值那么这条话的sql语句为:
select count(*) count_sum from v_alert_device where 1=1 and customer_id = 'hahaha' and alert_type_id = 123 order by count_sum desc LIMIT 10②不加where 1=1,并且假设customerId和alertTypeId没有值那么这条话的sql语句为:
select count(*) count_sum from v_alert_device where order by count_sum desc LIMIT 10那么就会报错。
③加了where 1=1,并且假设customerId和alertTypeId没有值那么这条话的sql语句为:
select count(*) count_sum from v_alert_device where 1=1 order by count_sum desc LIMIT 10则会返回table中的根据count_sum 降序的前十条值。
由此可以看出,where 1=1 这种写法 虽然给程序开发人员带来不便,还要避免sql注入的问题。
但 where 1=1 这种写法 也会给程序编写增加了方便。
本文介绍了在使用MyBatis进行数据库操作时,如何利用XML配置文件中的动态SQL特性来构造灵活的查询语句。特别是通过使用<if>标签来实现条件判断,确保即使在部分查询条件为空的情况下,SQL语句仍然能够正确执行。
1494

被折叠的 条评论
为什么被折叠?



