Search code examples
springjdbctemplate

Spring jdbcTemplate dynamic where clause


Is it possible to generate arbitrary where conditions 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 multiple 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.


Solution

  • 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...