mybatis使用Integer類型查詢可能出現(xiàn)的問題
使用Integer類型查詢出現(xiàn)的問題
mapper.xml :
<select id="count" parameterType="com.pinyu.system.web.page.Page" resultType="java.lang.Integer"> ?? ??? ?select count(m.id) from hr_push_msg_model as m ?? ??? ?<where> ?? ??? ??? ?<if test="page.keyword != null and page.keyword != ''"> ?? ??? ??? ??? ?m.text like '%${page.keyword}%' ?? ??? ??? ?</if> ?? ??? ??? ?<if test="page.entity != null"> ?? ??? ??? ??? ?<if test="page.entity.text != null and page.entity.text != ''"> ?? ??? ??? ??? ??? ?and ?m.text like '%${page.entity.text}%' ?? ??? ??? ??? ?</if> ?? ??? ??? ??? ?<if test="page.entity.title != null and page.entity.title != ''"> ?? ??? ??? ??? ??? ?and ?m.title like '%${page.entity.title}%' ?? ??? ??? ??? ?</if> ?? ??? ??? ??? ?<if test="page.entity.state != null and page.entity.state != ''"> ?? ??? ??? ??? ??? ?and ?m.state = #{page.entity.state} ?? ??? ??? ??? ?</if> ?? ??? ??? ??? ?<if test="page.entity.type != null and page.entity.type != ''"> ?? ??? ??? ??? ??? ?and ?m.type = #{page.entity.type} ?? ??? ??? ??? ?</if> ?? ??? ??? ?</if> ?? ??? ?</where> ?? ?</select>
比如:
<if test="page.entity.state != null and page.entity.state != ''"> ? ? ? ? ? ? ? ? ? ? and ?m.state = #{page.entity.state} ? ? ? ? ? ? ? ? </if>
當state這個值為0的時候
mybatis為默認為空字符串"",所以如果狀態(tài)這種類似的場景有0值得,查詢就不要加上xxxx!=""這種?;蛘遫r xxx==0
代碼示例:
1、
<if test="page.entity.state != null"> ? ? ?and ?m.state = #{page.entity.state} </if>
2、
<if test="page.entity.state != null and page.entity.state != '' or page.entity.state==0"> ? ? and ?m.state = #{page.entity.state} </if>
mybatis判斷Integer遇到的bug
場景產(chǎn)出
需要查出狀態(tài)為0的所有用戶
我是這樣寫的
1.mapper:
BaseUser selectUserByStatus(@parm("status") Integer status);
這里傳了0進去
2.sql:
SELECT * FROM base_user WHERE status=0
3.xml片段
<if test="status != null and status != ''"> status = #{status}, </if>
4.結(jié)果真正執(zhí)行的sql
SELECT * FROM base_user
小結(jié)一下:
test="status != null and status != ''"這個是拿來判斷String的?。?!也就是說Double,BigDecimal等數(shù)字類型也會出現(xiàn)這樣的情況
1.如果是Integer類型的話,如果變量的值是0,即 num = 0, mybatis在進行 num != '' " 的時候會認為 num 的值是空字符串;直接跳過判斷了
所以如果是Integer類型只需要判斷 != null 即可
2.如果String類型需要判斷不等于0,則需要寫name != '0'.toString(),否則會報錯。
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
java加載properties文件的六種方法總結(jié)
這篇文章主要介紹了java加載properties文件的六種方法總結(jié)的相關(guān)資料,需要的朋友可以參考下2017-05-05spring?boot?executable?jar/war?原理解析
spring boot里其實不僅可以直接以 java -jar demo.jar的方式啟動,還可以把jar/war變?yōu)橐粋€可以執(zhí)行的腳本來啟動,比如./demo.jar,這篇文章主要介紹了spring?boot?executable?jar/war?原理,需要的朋友可以參考下2023-02-02SpringBoot處理JSON數(shù)據(jù)方法詳解
這篇文章主要介紹了SpringBoot整合Web開發(fā)中Json數(shù)據(jù)處理,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2022-10-10Java?CopyOnWriteArrayList源碼超詳細分析
為了將讀取的性能發(fā)揮到極致,jdk中提供了CopyOnWriteArrayList類,下面這篇文章主要給大家介紹了關(guān)于java中CopyOnWriteArrayList源碼解析的相關(guān)資料,文中通過實例代碼介紹的非常詳細,需要的朋友可以參考下2022-11-11