Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Like clause

Tags:

java

spring

jdbc

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.

like image 381
Chris Avatar asked Jul 14 '10 13:07

Chris


People also ask

How do I create a JPA query?

You can use either named-query XML element or @NamedQuery annotation to create named queries with the JPA query language. You can use either named-native-query XML element or @NamedNative query annotation to create queries with SQL if you are ready to tie your application with a specific database platform.

How does JPA findById work?

Its findById method retrieves an entity by its id. The return value is Optional<T> . Optional<T> is a container object which may or may not contain a non-null value. If a value is present, isPresent returns true and get returns the value.

What is native query in JPA?

Native query refers to actual sql queries (referring to actual database objects). These queries are the sql statements which can be directly executed in database using a database client.


1 Answers

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);
like image 183
Jeff Avatar answered Nov 03 '22 21:11

Jeff