tags:

views:

44

answers:

2
+2  Q: 

Spring Like clause

I am trying to use a MapSqlParameterSource to create a query using a Like clause.

The code is something like this. The function containing it receives nameParam:

String namecount = "SELECT count(*) FROM People WHERE LOWER(NAME) LIKE :pname ";

String finalName= "'%" +nameParam.toLowerCase().trim() + "%'";

MapSqlParameterSource namedParams= new MapSqlParameterSource();

namedParams.addValue("pname", finalName);

int count= this.namedParamJdbcTemplate.queryForInt(namecount, namedParams);

This does not work correctly, giving me somewhere between 0-10 results when I should be receiving thousands. I essentially want the final query to look like:

SELECT count(*) FROM People WHERE LOWER(NAME) LIKE '%name%'

but this is evidently not happening. Any help would be appreciated.

Edit:

I have also tried putting the '%'s in the SQL, like

 String finalName= nameParam.toLowerCase().trim();

 String namecount = "SELECT count(*) FROM People WHERE LOWER(NAME) LIKE '%:pname%' "

;

but this does not work either.

A: 

Have you tried placing the % wild cards in your sql string (not the bind variable value itself):

String finalName= nameParam.toLowerCase().trim();
String namecount = "SELECT count(*) FROM People WHERE LOWER(NAME) LIKE '%:finalName%'";
Brian
Can you suggest a way to modify the existing code so that I can use the '?' placeholder? I don't believe you can use it with a MapSqlParameterSource. Thanks
Chris
is `LIKE %:pname%` valid?
matt b
I've tried that. It gave me similar (possibly same) results. I think there must be something with the single quotes or the '%' signs that interfere with the query.
Chris
You can't leave the variable with % though, so you now need:String finalName= nameParam.toLowerCase().trim(); The wild cards are not removed from the finalName variable. Updated my answer.
Brian
Thank you, I see that my edit was unclear but I meant to reflect that I had essentially tried what you are suggesting but it still does not work. Do you have any other suggestions?
Chris
+1  A: 

You don't want the quotes around your finalName string. with the named parameters you don't need to specify them. This should work:

String namecount = "SELECT count(*) FROM People WHERE LOWER(NAME) LIKE :pname ";
String finalName= "%" + nameParam.toLowerCase().trim() + "%";

MapSqlParameterSource namedParams= new MapSqlParameterSource();
namedParams.addValue("pname", finalName);

int count= this.namedParamJdbcTemplate.queryForInt(namecount, namedParams);
Jeff
You are my hero. Thanks a lot. I've been working on this for an embarassingly long period of time.
Chris
how about some accepted answer love?
Jeff