1:動態SQL遇到的坑,先看下面OGNL運算式的說明,
Any object can be used where a boolean is required. OGNL interprets objects as booleans like this:
-
If the object is a Boolean, its value is extracted and returned;
-
If the object is a Number, its double-precision floating-point value is compared with zero; non-zero is treated as true, zero as false;
-
If the object is a Character, its boolean value is true if and only if its char value is non-zero;
-
Otherwise, its boolean value is true if and only if it is non-null.
如果物件是一個Number型別,值為0時將被決議為false,否則為true,浮點型0.00也是如此,OGNL對于boolean的定義和JavaScript有點像,即'' == 0 == false,這也就不難理解<if test="status != null and status !=''">and status = #{status}</if>當status=0時出現的問題了,顯然0!=''是不成立的,導致運算式的值為false,
將運算式修改為<if test="status != null">and status = #{status}</if>該問題便迎刃而解,該問題的根源還是來自編碼的不規范,只有String型別才需要判斷是否!='',其他型別完全沒有這個必要,可能是開發人員為了省事直接復制上一行拿過來改一改或是所使用的MyBatis生成工具不嚴謹導致該問題的發生,
這里有必要再提一個“坑”,如果你有類似于String str ="A"; <if test="str!= null and str == 'A'">這樣的寫法時,你要小心了,因為單引號內如果為單個字符時,OGNL將會識別為Java 中的 char型別,顯然String 型別與char型別做==運算會回傳false,從而導致運算式不成立,解決方法很簡單,修改為<if test='str!= null and str == "A"'>即可,
2:集合中移除某些無用的資料的操作,
//正確寫法 List<Stu1> list = new ArrayList<>(); list.add(new Stu1("zhangsan", 21)); list.add(new Stu1("lisi", 22)); list.add(new Stu1("zhangsan", 26)); Iterator<Stu1> iterator = list.iterator(); while (iterator.hasNext()) { Stu1 stu1 = iterator.next(); if (stu1.getName().equals("zhangsan1")) { iterator.remove(); } } //錯誤寫法,用foreach回圈遍歷集合,我就不寫了.這樣可能會報例外的, // 開發中移除集合中的元素的時候,用Iterator來遍歷集合,
3:字串變數和字串常量equals的時候將字串常量寫在前面
String str = "123" ; if(str.equals("123")){ } // 建議修改為這樣主要是可以避免空指標例外, String str = "123" ; if("123".equals(str)){ }
4:HashMap用物件作為key的時候重新equal和hashCode,如果不重寫hashcode方法get的結果將為null,
如下圖是怎樣重寫equal和hashCode的方法,

注意:平常用物件判斷是否相同的時候,一般也會重寫這個物件的equal和hashCode的方法,一般的開發工具也都有重寫這兩個方法的快捷鍵,
5:用最有效的方式來遍歷map集合
如下,資料量大的時候用Iterator遍歷map的效率較高:
Map<String, String> hm = new HashMap<>(); hm.put("1", "aa"); hm.put("2", "bb"); Set<Map.Entry<String, String>> entries = hm.entrySet(); Iterator<Map.Entry<String, String>> iterator = entries.iterator(); while (iterator.hasNext()) { Map.Entry<String, String> map = iterator.next(); System.out.println("key值" + map.getKey()); System.out.println("value值" + map.getValue()); }
6:Oracle查詢優化:
選擇最有效率的表名順序:ORACLE的決議器按照從右到左順序處理from字句中的表名,from字句中寫在最后的表(基礎表)將最先被處理,在from字句中包含多個表的情況下,必須選擇記錄數最少的表作為基礎表,如果有3個以上的表連接查詢,那就需要選擇交叉表作為基礎表,交叉表就是那個被其他表參考的表,
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/545164.html
標籤:Java
