user2572003
user2572003

Reputation: 741

How do i form a query for jdbcTemplate

am trying to form a query based on parameters, if the parameters for WHERE clause is null or not. it seems to be a huge code if i do this on if and else. Is there any other smart way to this??

example :

String query = "SELECT CUSTOMER_NAME FROM CUSTOMER_TABLE WHERE ";
if(cust_id !=null && !(cust_id.trim().equalsIgnoreCase("")))
{
    query = query + "cust_id='"+cust_id+"'";    
}
else
{

}

checking all the columns like this, the code is looking like a mess, please let me know if there is an other way to do this

adding to the above question :

I also have the parameters for like operator

example

if(strCustName!=null)
{
    String query = "SELECT * FROM CUSTOMER WHERE CUSTOMER_NAME LIKE '"+strCustName+"';
}

Upvotes: 0

Views: 148

Answers (1)

StanislavL
StanislavL

Reputation: 57381

You can use NamedParameterJDBCTemplate

And your query could be

... WHERE (cust_id=:custIdParam OR :custIdParam is null)
      AND (another_column=:another_param OR :another_param is null)

UPDATE:

String sqlstr = "select * from the_table where lastname like :lastname or :lastname is null"

NamedParameterJdbcTemplate jt = new NamedParameterJdbcTemplate(datasource);

Map namedParameters = new HashMap();
namedParameters.put("lastname", "%test%");
SqlRowSet result = jt.queryForRowSet( sqlstr ,namedParameters );

from the link

Upvotes: 1

Related Questions