今天碰到个问题上关于sql搜索空值的。举个简单的例子,当我使用mybatis时,
我将sql语句配置在xml里面。
比如我的搜索语句是:
select * from user where id=#{id};(当然实际使用的不是这么简单的语句,这只是个例子)
但是如果传的id为null话,拼接起来得sql语句去执行就会报错,有什么办法可以解决
这个问题吗?
<if test="id != null">id = #{id}</if>
用 判断, 空值不参与查询条件的拼接
函数使用非空注解 修饰
https://blog.csdn.net/laifu007/article/details/73220102?utm_source=itdadao&utm_medium=referral
说明下如果是单个基本类型参数那么只能用value。
<if test="value != null">
select * from user where id=#{id};
</if>
select * from user where id=#{id};
这个看写这个SQL的需求,如果id为null时不需要返回任何结果,就不必要查询,在代码中判断id为null时直接返回空列表就行
如果id为null时想要返回所有数据,类似于select * from user可以添加一个mybatis的if标签,如下:
select * from user
id=#{id}
你是想查询id为null的还是 避免查询id为null时报错
select * from aaa where a1=#{a} and b1=#{b}
select * from aaa
《where》
//判断为不为null并且不为'' 不需要''可以去掉
《if test="a!=null and a!=''"》
and a1=#{a}
《/if》
《if test="b!=null and b!=''"》
and b1=#{b}
《/if》
尖括号会消失
提交的数据最好先校验漫步满足条件,如果满足条件再做下面的操作!比如id可以使用if判断再执行查询操作。
select * from user where
id=#{id};
name=#{name};
mapping.xml里面就这样写,传了哪个参数就用哪个参数,
id = #{id} 最好是写成 where 1=1 and id = #{id} 防止后面没有执行报错