Java MyBatis Sql查询时的判空问题
场景
查询一个student
代码
<select id="selectStudentByParams" resultType="...">
select * from t_student
<where>
1=1
<if test="username != null and username != ''">
and username = #{username}
</if>
...
</where>
</select>
解释
username != null and username != ''
首先判断是否为null
,然后判断如果存在判断是否为空,前端如果穿了个空的username
也可以接着查询.
至于username.trim() != ''
考虑数据库中,前端传的会不会有前导的空格或后缀空格,如果没有就没必要.trim()
处理
当然也可以 and username != ''
也可以,但是必须要在controller
层进行判断处理空字符串的情况.
rds_blogs