现在的位置: 首页 > 综合 > 正文

ibatis学习(四)—ibatis3用like进行模糊匹配检索的写法

2013年10月19日 ⁄ 综合 ⁄ 共 1179字 ⁄ 字号 评论关闭

其实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("\\", "\\\\") 即可。

抱歉!评论已关闭.