How to search string LIKE 'something%' with Java Spring Framework?
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<Foo> getByName(List<Integer> codes, String namePart) { String sql = "select * from FOO where CODE in (:codes) and NAME like :name" Map<String,Object> params = new HashMap<String,Object>(); 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?
For named parameters to work, you need to use NamedParameterJdbcTemplate
params.put("name", "Joe%");jdbcTemplate.query("select * from FOO where CODE in (:codes) and NAME like :name"
In another form, I encountered the same problem, and I tried to solve it via this manner:
public List<MyEntity> getMyEntityValuesBySearchText(String searchText) { String query = "SELECT * FROM MY_ENTITY_TABLE WHERE NAME LIKE ?"; return this.getJdbcTemplate().query(query, new String[] { "%" + searchText + "%" }, (rs, rowNum) -> new MyEntity(rs.getLong("PK"), rs.getString("NAME")));}