前言
最近項目內更新數據時,發現數字類型字段設置為0時不能正常的更新進數據庫,我們打印了下mybatis的sql日志發現字段為0的sql沒有被拼接。
樣例
下面的是錯誤示例 ?
1
2
3
4
5
6
7
8
9
|
<update id= "update" parameterType= "com.chengfengfeng.test.domain.People" > update people set < if test= "age!=null and age !=''" > age=#{age}, </ if >, modified = sysdate() where user_id = #{userId} </update> |
age是個int類型的數據,我們在寫age判斷的時候就增加上了判斷age!=''
,這個是存在問題的。
正確的示例 ?
1
2
3
4
5
6
7
8
9
|
<update id= "update" parameterType= "com.chengfengfeng.test.domain.People" > update people set < if test= "age!=null" > age=#{age}, </ if >, modified = sysdate() where user_id = #{userId} </update> |
原因是什么呢
跟蹤了下代碼,發現在解析xml時數字類型會走下面的判斷
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
public abstract class OgnlOps implements NumericTypes { //省略其他無用代碼 public static double doubleValue(Object value) throws NumberFormatException { if (value == null ) { return 0 .0D; } else { Class c = value.getClass(); if (c.getSuperclass() == Number. class ) { return ((Number)value).doubleValue(); } else if (c == Boolean. class ) { return (Boolean)value ? 1 .0D : 0 .0D; } else if (c == Character. class ) { return ( double )(Character)value; } else { String s = stringValue(value, true ); //這個位置會把'‘空串處理成0 return s.length() == 0 ? 0 .0D : Double.parseDouble(s); } } } } |
我們看上面最后一段代碼,會把''
轉換成0.0D
,那么我們的最開始的if判斷就變成了age != 0
,所以當我們把age設置為0時,結果就變成了false,導致sql不會進行拼接,更新數據失敗。
到此這篇關于mybatis寫xml時數字類型千萬別用 !=‘‘(不為空串)進行判斷的示例詳解的文章就介紹到這了,更多相關mybatis寫xml數字類型內容請搜索服務器之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持服務器之家!
原文鏈接:https://blog.csdn.net/qq_30062181/article/details/108707733