是这样,最近有个需求是,如果用户在搜索框里面输入的是一个空格那就搜索值为空的数据,但是我在mybatis里面写if判断,总是不生效求大神帮忙看下,屁话少说,我上代码!
<if test="orderRemark !=null and orderRemark !=''">
and a.order_Remark like '%${orderRemark}%'
</if>
传入一个空字符串(没有空格),翻译出来的sql语句是,and a.order_Remark like '%%'
然后我又改了下
<if test="orderRemark !=null and orderRemark !=''">
<choose>
<when test="orderRemark==' '">
and a.order_Remark like ='' or a.order_Remark is null
</when>
<otherwise>
and a.order_Remark like '%${orderRemark}%'
</otherwise>
</choose>
</if>
这时候我传进去一个带有空格的字符串
翻译出来的是 and a.order_Remark like '% %'
既然第二个已经有空格了,为什么没进when的判断呢?????
求大神帮忙啊!!!!!!!!!!!!!!!
You can use the trim() method to remove spaces before passing parameters, so there is no need to judge in mybatis
I checked on Baidu and found this issue on Google.
So I tried the solution myself. When I first started testing, I found that if I judged a space (
' '
) in the when of xml, I couldn't judge it, but I could judge two spaces.I thought it was strange at the time, so I wondered if it was because of the single quotes. Then I thought about how single quotes represent characters in Java, so how can they be compared with strings. So I added
' '
after a space (toString()
), like this<when test="orderRemark==' '.toString()">
and that’s it.So I guess if there is one space, it defaults to characters, and if there are more than two spaces, it will be converted to a string. My guess, please correct me.
If this is very troublesome, just make a judgment in the java code, or if it is judged to be empty, just use a special character. Don't judge the null character, and be flexible