java 字符串 like,如何使用Java Spring Framework搜索字符串LIKE'something%'?

I've got a MySQL table with Foos. Each Foo has a numeric non-unique code and a name. Now I need to find if any Foo with one of certain codes happens to have a name that starts with a given string. In normal SQL this would be trivial:

select * from FOO where CODE in (2,3,5) and NAME like 'bar%';

But how would I properly do this in Spring now? Without the need for the 'like' operator I'd do it like this:

public List getByName(List codes, String namePart) {

String sql = "select * from FOO where CODE in (:codes) and NAME=:name"

Map params = new HashMap();

params.put("codes", codes);

params.put("name", namePart);

return getSimpleJdbcTemplate().query(sql, new FooRowMapper(), params);

}

However, with 'like' nothing seems to work: NAME like :name%, NAME like ':name%', or NAME like ?% when using the placeholders instead of named parameters.

I could be brutal and enter it as

String sql = "select * from FOO where CODE in (:codes) and NAME like '"+namePart+"%'";`

but obviously it would be more than nice if Spring would sanitize the input parameters properly etc, you know...

You'd think Spring would support this somehow but I cannot figure it out.

解决方案

Wait, of course I had to "try one more final thing" before calling it a day, and lo and behold, all my unit tests suddenly pass:

public List getByName(List codes, String namePart) {

String sql = "select * from FOO where CODE in (:codes) and NAME like :name"

Map params = new HashMap();

params.put("codes", codes);

params.put("name", namePart+"%");

return getSimpleJdbcTemplate().query(sql, new FooRowMapper(), params);

}

I didn't think of entering the "%" in the parameter, I was certain Spring would automatically escape it. I wonder if I'm doing it right?

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值