← Java / Spring · Contents

JAVA-004 / Intermediate

MyBatis ORDER BY ${sort} column injection

A03:2021 Injection · CWE-89 SQL Injection

Why is this a problem?

Identifiers cannot be bound with #{}, so using ${} may turn raw input into SQL.

How to fix it

java
// Service-layer allowlist
Map<String,String> SORT = Map.of("created", "created_at", "title", "title");
String col = SORT.getOrDefault(sort, "created_at");
xml
<select id="list" resultType="Post">
  SELECT * FROM post ORDER BY ${sortColumn}   <!-- Only values that pass the allowlist -->
</select>

Further reading