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

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




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值