Anurag Ambuj
Anurag Ambuj

Reputation: 121

Dynamic column name compared with value in where clause using MyBatis

Is it possible to use something like

SEARCH_QUERY = "select * from info where #{columnName}=\"#{columnValue}\"";

using MyBatis 3 ?

The columnName needs to be dynamic.

Thanks!

Upvotes: 0

Views: 1063

Answers (1)

When you use syntax like #columnValue mybatis will create prepared statement and will bind the variable for you. This has several consequences:

  1. you don't need to put quotes around #columnValue
  2. you don't need to escape values passed
  3. # can only be used where the parameter in JDBC query is allowed. So you can't use it to generate dynamic column name

If you want to generate dynamic query use $columnName instead. The complete query would look like:

select * from info where ${columnName}=#{columnValue}

Important thing to remember is that ${columnName} is put to query verbatim very much like string concatenation if you would use JDBC directly so it is vulnerable to the SQL injection if columnName is something provided by user.

Upvotes: 4

Related Questions