IBATIS中關於iterate和‘$’與‘#’的應用

IBATIS中關於iterate和‘$’與‘#’的應用

一個包含List元素的HashMap參數賦給sqlMap
public int getCountById(String id, String title, List ids) throws Exception {  
Map paramMap=new HashMap();  
paramMap.put("id", id);  
paramMap.put("title", title);  
paramMap.put("ids",ids);  
return (int) this.sqlMapClient.queryForObject("getCountById", paramMap);  

上面的ids元素是一個List,裏面包含了一個id列表。id和title都是String。

<select id="getOrderformByBiOid" parameterClass="java.util.HashMap" resultMap="Result">  
select *   
from MYTABLE     
<dynamic prepend="where">  
<isNotNull prepend="and" property="id">  
ID=#id#  
</isNotNull>  
<isNotNull prepend="and" property="title">  
TITLE like '%$title$%' 
</isNotNull>  
<isNotNull prepend="and" property="ids">  
IDS in  
<iterate  property="ids" open="(" close=")" conjunction=",">  
#ids[]#  
</iterate>  
</isNotNull>  
</dynamic>  
order by TIME DESC  
</select> 
在上面的sqlMap中要注意的地方有兩個。第一個地方是,<iterate>標籤中一定要記得寫property="ids",不要因爲在上面的
<isNotNull prepend="and" property="ids">標籤中判斷了該屬性,就在<iterate>這個標籤中忽略了property的書寫(如果你忘了
寫iterate中的property屬性的話系統會報這樣的錯誤Cause: com.ibatis.sqlmap.client.SqlMapException: ParameterObject or
property was not a Collection, Array or Iterator.),並且要記住,
#ids[]# 中的‘[]’符號,只有這樣ibatis才把ids作爲一個可迭代的對象(list,數組...),不然的話ibatis會把ids作爲普通的string來處理。
第二個地方就是,上面的關於‘$‘與‘#’的應用。
下面就來說說關於‘$‘與‘#’的應用。在通常情況下ibatis的參數在sqlmap中使用#param#的形式,參數名以’#‘包着,但當使用
sql的like語句時就發生了問題,在單引號中無法使用#param#這種形式。解決辦法有:
1.當應用select * from  table1 where  col like ’value%’時,如果要把‘value’以參數代替,可以把整個like後面的字符串
全改爲參數。即:select * from  table1 where  col like #param#  ,此時參數param的值爲字符串"value%"
2.使用‘$’將參數名包起來。例如:name like ‘%#name#%’。我們的解決方法有2。(a)把name like ‘%#name#%’的
#換成$,即:name like ‘%$name$%’。(b)用||連接字符串的方式,寫成,name like ‘%’|| #name#‘%’。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章