使用mybatis来有选择性的查询,使用if构造条件语句

现在有这么一个需求,前端指定条件查询。比如说前端指定了name,age这两个字段来查询,但还有一些别的字段比如说sex,color等。这个时候就需要我们用动态sql来写查询语句

直接展示正确的mapper.xml代码

<select id="mapper.java对应的方法名" resultType="结果映射的类">
	select
		*
	from
		user
	<where>
		1=1
		<if test="name != null and name != ''">
			and name = #{name}
		</if>
		<if test="age != null and age != ''">
			and age = #{age}
		</if>
		<if test="sex != null and sex != ''">
			and sex = #{sex}
		</if>
		<if test="color != null and color != ''">
			and color = #{color}
		</if>
	</where>
</select>

为什么我会记录这么一个动态sql呢,当然是我在这里耗了一个多小时解决报错

一开始我是这么写的

<select id="mapper.java对应的方法名" resultType="结果映射的类">
	select
		*
	from
		user
	where
		1=1
		<if test="name != null">
			and name = #{name}
		</if>
		<if test="age != null">
			and age = #{age}
		</if>
		<if test="sex != null">
			and sex = #{sex}
		</if>
		<if test="color != null">
			and color = #{color}
		</if>
	
</select>

这个时候是没有报错的,一定情况下也是可以正常运行的。这个情况只是所有条件都有值,在控制台你可以看到where的4个条件。

假如你只查name,执行后你会发现,控制台报错,同时在报错前打印的sql你会发现where的四个条件都写出来了,if就和摆设一样

所以正确的写法是

<where>
	<if test="条件">
		条件为真时,把该区域代码拼接到sql中
	</if>
</where>

※※※※※※ 重要 ※※※※※※※

在if的条件中,name不为空拼接if中的代码这里,

name != null 只是这么写不行,name参数为空,这是判断传入传入的那么是否不等于null,还需要拼接上and name!= ‘’,两个合并一起表示不为空,经过测试是可行的

  • 8
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值