Hint
This article is generated by AI translation.
SQL Injection
Please note
SQL injection is dangerous. You must ensure injected content is safe.
Use ${...} to fetch named arguments and inject the result into SQL text.
Example: Argument-driven sorting via SQL injection
select * from users where id > #{id} order by ${order}
Basic Usage
Map<String, Object> args = CollectionUtils.asMap(
"id", 2,
"order", "name desc"
);
jdbcTemplate.queryForList("select * from users where id > #{id} order by ${order}", args);
Common Scenarios
${...} is suitable for scenarios where the SQL structure itself needs to change dynamically, for example:
Dynamic table name
select * from ${tableName} where id = #{id}
Dynamic column names
select ${columns} from users where id = #{id}
Dynamic ordering
select * from users order by ${orderBy}
Difference from #{...}
| Syntax | Behavior | Safety |
|---|---|---|
#{...} | Generates a ? placeholder and binds the argument value via PreparedStatement | Safe, prevents SQL injection |
${...} | Evaluates via OGNL and splices the result directly into the SQL string | Unsafe, SQL injection risk |
Principle
Prefer #{...}. Only use ${...} when the SQL structure (table name, column name, ordering, etc.) needs to change dynamically.