Spring jdbcTemplate dynamic where clause

minil picture minil · May 22, 2011 · Viewed 12.2k times · Source

Is it possible to generate arbitrary where condtions SQL query through Jdbc template:

example:

If i pass value for 1 parameter (only name) : search by name

"select * from address where shopname = ?";

If i pass value for 2 parameter (name and city) - search by shopname and city:

"select * from address where shopname = ? and city = ?";

I have mupliple search fields. 7 fields. If user enters any combination. i have search only based on parameter. How to dynamically pass the parameters to the sql. Need snippet/Example how to achieve this.

Answer

hvgotcodes picture hvgotcodes · May 22, 2011

What you want is some sort of criteria building api, which Hibernate has. Unfortunately, I don't think Spring's JdbcTemplate has any such facility. Others will correct me if I'm wrong...