how to pass LIKE parameters (values) in NamedParameterJdbcTemplate in Spring

Imagine we have a query

SELECT * FROM ARTICLE WHERE TITLE LIKE ‘%spring%’

As we are using NamedParameterJdbcTemplate, I’d like to pass title as a parameter named title holding the value.

So the query would now be SELECT * FROM ARTICLE WHERE TITLE LIKE ‘%:title%’

Solution:
We have to frame the query as like below in Spring JDBC Code

String final GET_QUERY = "SELECT * FROM ARTICLE WHERE TITLE LIKE '%'||:title||'%'";

So, in our spring code

MapSqlParameterSource parameters = new MapSqlParameterSource();
parameters.addValue("title", title);

NamedParameterJdbcTemplate npjt = new NamedParameterJdbcTemplate(
getJdbcTemplate().getDataSource());
list = npjt.query(
GET_QUERY, parameters,
new RowMapper() {....});

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: