其實ibatis的文檔中明確說明了參數的使用方法,有部分工作是留給我們自己做的,下面是說明文檔的內容:
Notice the parameter notation:
#{id}
This tells MyBatis to create a PreparedStatement parameter. With JDBC, such a parameter would be
identified by a “?” in SQL passed to a new PreparedStatement, something like this:
// Similar JDBC code, NOT MyBatis…
String selectPerson = “SELECT * FROM PERSON WHERE ID=?”;
MyBatis 3 - User Guide
5 November 2010 23
PreparedStatement ps = conn.prepareStatement(selectPerson);
ps.setInt(1,id);
Of course, there’s a lot more code required by JDBC alone to extract the results and map them to an
instance of an object, which is what MyBatis saves you from having to do. There’s a lot more to know
about parameter and result mapping. Those details warrant their own section, which follows later in
this section.
所以解決的思路是:sql中應該跟正常的替換方式相同,ibatis並沒有提供特殊寫法,應該在傳入的參數上下功夫。
也就意味着需要自己來做轉譯如:
SqlMap中的sql語句爲:
select * from A where A.name like #{key}#
java端對Key值進行轉譯:
public static String transfer(String keyword) {
if(keyword.contains("%") || keyword.contains("_")){
keyword = keyword.replaceAll("\\\\", "\\\\\\\\")
.replaceAll("\\%", "\\\\%")
.replaceAll("\\_", "\\\\_");
}
return keyword;
}
然後再轉譯後的key上,按照邏輯添加“%”或者“_”,再設置到statement中即可。
key ="%"+ transfer(key) + "%";
注意:上面的轉譯方法適用於jdk1.6,之前的可能需要將第一個.replaceAll("\\\\", "\\\\\\\\")
改成:.replaceAll("\\", "\\\\") 即可。