Scrivio Interview library
ScenarioAdvanced7 min read · updated 12 November 2026

You inherit 200 MyBatis XML mapper files where many queries use ${} for filters and sort columns, and a penetration test found SQL injection. How do you fix and prevent this at scale?

We find every ${ in the mapper XML files and annotations, classify each use as either a value or an identifier, replace values with #{} parameters, and for identifiers such as sort columns map user input to a fixed whitelist in Java before it reaches the mapper. Then we stop the problem coming back with a build check that fails on any new ${} without an approved marker, add tests that send injection payloads to the fixed endpoints, and track the work with the security team, internet-facing endpoints first.

Why this question is asked

A penetration test that finds SQL injection is serious, but in a codebase of 200 mapper files the finding is rarely a single bug. It usually reveals a habit: someone once used ${} because it was convenient, others copied it, and now it is everywhere. Interviewers ask this scenario because fixing a pattern at scale, and keeping it fixed, is harder than fixing one query. In this answer, we will recap why ${} is dangerous, then go through finding and classifying every use, the two kinds of fix, the build check that prevents regressions, the tests that prove the fixes, and how to run the remediation with the security team.

1A Quick Recap of Why ${} Is Dangerous

In MyBatis, #{name} becomes a ? placeholder in a PreparedStatement and the value is bound separately, so it can never change the SQL. ${name} is plain text substitution: the value is pasted into the SQL string before it is sent. If any part of that value comes from a request, an attacker can close our quote and add their own SQL.

XML
<!-- A typical finding -->
SELECT * FROM orders WHERE status = '${status}' ORDER BY ${sort}
// status = "x' UNION SELECT username, password_hash, null FROM users --"
// SELECT * FROM orders WHERE status = 'x' UNION SELECT username, password_hash, null FROM users --' ORDER BY ...

Notice that the same statement has two different kinds of ${}. The status is a value and never needed ${} at all. The sort is an identifier, a column name, which placeholders cannot express, so it needs a different fix.

2Finding and Classifying Every Use

We start with a complete list, generated by a tool rather than by reading files. A search over the XML mappers and over Java sources finds both XML statements and annotation-based mappers, including SQL providers that build strings in Java.

Java
# Every ${ in XML mappers and Java mapper annotations, with file and line
grep -rn --include='*.xml' '\${' src/main/resources/mappers | wc -l # 312
grep -rn --include='*.java' '\${' src/main/java | grep -E '@(Select|Update|Insert|Delete)' | wc -l # 41
Classifying each ${} finding
Pattern foundKindFix
status = '${status}'Valuestatus = #{status}
id IN (${ids})Value list<foreach> with #{id} items
LIKE '%${term}%'ValueLIKE CONCAT('%', #{term}, '%') or <bind>
ORDER BY ${sort} ${dir}Identifier and keywordWhitelist in Java, then ${}
FROM ${tableName}IdentifierWhitelist or separate statements
Values never need ${}; identifiers need a whitelist.

Each hit goes into a tracking sheet with its location and a classification. A value is anything that could be a bound parameter: ids, statuses, dates, search terms. An identifier is a column, table or schema name, or a keyword such as ASC or DESC. A third group, ${} that only receives constants from our own code, still gets the identifier fix, because 'only our code calls this' tends to stop being true. We also record which HTTP endpoints reach each statement, which drives the priority.

3Fix 1: Turn Values Into Parameters

Most findings are values, and their fix is mechanical: replace ${} with #{} and remove the quotes that were around it, since the driver handles quoting. Lists become <foreach> loops, and LIKE patterns keep the wildcard outside the bound value.

XML
<!-- Before -->
WHERE customer_id IN (${ids}) AND name LIKE '%${term}%'
<!-- After -->
WHERE customer_id IN
<foreach collection="ids" item="id" open="(" separator="," close=")">#{id}</foreach>
AND name LIKE CONCAT('%', #{term}, '%')
// SQL sent: WHERE customer_id IN (?, ?, ?) AND name LIKE CONCAT('%', ?, '%')

Callers that passed a pre-joined string such as "1,2,3" must now pass a List, changed in the same pull request.

4Fix 2: Whitelist Identifiers in Java

For identifiers, the mapper still uses ${}, but the value can only come from a fixed set we define. The controller accepts the user's choice as a name, and Java translates it to a real column.

Java
public enum OrderSortColumn {
CREATED("o.created_at"), TOTAL("o.total_amount"), STATUS("o.status");
public final String column;
OrderSortColumn(String column) { this.column = column; }
public static OrderSortColumn parse(String input) {
try { return valueOf(input.toUpperCase(Locale.ROOT)); }
catch (IllegalArgumentException e) { return CREATED; } // unknown input -> safe default
}
}
// In the mapper: ORDER BY ${sort.column} ${dir.sql} <!-- safe-identifier: OrderSortColumn -->
mapper.search(filter, OrderSortColumn.parse(request.sort()), SortDirection.parse(request.dir()));

Notice that the mapper parameter is now an enum, not a String. That makes the safe path the only path: nobody can pass raw request text to that statement without the compiler complaining. The comment next to the ${} names the whitelist, which the build check in the next section looks for.

5Preventing New ${} With a Build Check

Fixing 350 findings is wasted if new ones arrive next month. We add a check that runs in every build and fails on any ${ that does not carry an approved marker. It can be a small JUnit test that scans the mapper resources, which needs no new tooling, or a rule in a static analysis tool the company already uses, such as Semgrep or a custom SpotBugs or Sonar rule.

Java
@Test
void noUnapprovedDollarSubstitutionInMappers() throws IOException { // numberedLines(p): small helper, one record per line
try (Stream<Path> files = Files.walk(Path.of("src/main/resources/mappers"))) {
List<String> offenders = files.filter(p -> p.toString().endsWith(".xml"))
.flatMap(p -> numberedLines(p).filter(l -> l.text().contains("${") && !l.text().contains("safe-identifier:"))
.map(l -> p.getFileName() + ":" + l.number()))
.toList();
assertThat(offenders).isEmpty(); // fails the build, listing file:line for each new use
}
}

During the remediation, the check starts with a baseline file of known findings so the build stays green, and the baseline shrinks with every fix. Once it is empty, it is deleted, and any new ${} needs a marker that names its whitelist, which a reviewer can verify.

6Proving the Fixes With Injection Tests

Each fixed endpoint gets integration tests that send classic payloads against a real database in Testcontainers. The test asserts that the response is a normal empty result or a validation error, never extra rows, and never a database syntax error, which would show that text still reaches the SQL.

Java
@ParameterizedTest
@ValueSource(strings = {"'", "x' OR '1'='1", "x' UNION SELECT null--", "1; SELECT pg_sleep(5)--"})
void statusFilterIsNotInjectable(String payload) {
var response = client.get().uri("/orders?status={s}", payload).retrieve().toEntity(String.class);
assertThat(response.getStatusCode().value()).isIn(200, 400); // never 500 from a SQL error
assertThat(response.getBody()).doesNotContain("password_hash");
}

7Running the Remediation With Security

The work is tracked jointly with the security team, with the sheet from the first step as the single list. We prioritise by exposure: statements reachable from internet-facing endpoints without authentication first, then authenticated external endpoints, then internal tools, then batch jobs with no user input. The reported finding itself is fixed first, within days.

We report progress as numbers the security team can follow, for example 350 findings, 120 fixed, 0 remaining on public endpoints, and ask them to retest the original finding and a sample of the fixes. A short team guideline with the #{} rule, the whitelist pattern and the build check closes the loop.

Step throughRemediation order
  1. Fix and deploy the reported findingdays, then security retests
  2. Inventory every ${} with file, statement and endpoint
  3. Fix public, unauthenticated endpoints first
  4. Then authenticated external, internal, batch
  5. Build check with a shrinking baselineempty baseline, then no new ${} without a marker
  6. Injection tests and security retest of a sample

6 steps in order. Play them, or step through them one at a time.

8Follow-up questions

Could a web application firewall solve this instead?

A firewall can block some obvious payloads and is a reasonable short-term layer while fixes roll out, but it cannot be the fix. Attackers vary payloads, and the firewall does not know which parameters reach a ${}. Only binding values as parameters removes the vulnerability itself.

What about tables chosen dynamically, for example one per tenant?

If the table name truly varies, the same whitelist rule applies: the tenant id is validated and mapped to a known table name pattern in Java, ideally from a registry of tenants, before reaching the mapper. Often the better long-term design is a tenant column with a bound parameter, or a schema per tenant selected by the connection, so no identifier is built from input at all.

9Conclusion

In this answer, we handled widespread ${} use in MyBatis as a pattern rather than a single bug. We listed every occurrence with tooling, classified each as a value or an identifier, replaced values with #{} parameters and mapped identifiers through a Java whitelist such as an enum. A build check with a shrinking baseline stops new ${} without an approved marker, injection tests against a real database prove the fixes, and the work is tracked with security, starting with the reported finding and internet-facing endpoints.

What to say in the interviewAbout 90 seconds aloud

Open with

First I would fix and deploy the specific finding from the penetration test, since it is known to be exploitable. Then I would get a full inventory: grep every mapper XML and every annotation-based mapper for ${, plus SQL providers, and record each hit with the statement and which endpoint reaches it.

Then, if they want more

I would classify each one. Values like ids, statuses and search terms never needed ${}, so they become #{}, with foreach for lists and CONCAT or bind for LIKE patterns.

Identifiers like sort columns and directions cannot be bound, so the mapper keeps ${}, but the parameter becomes an enum that maps the user's choice to a fixed column name, with a safe default for unknown input.

To stop it coming back, I would add a build check, even a simple JUnit test that scans the mapper files and fails on any ${ without a marker naming its whitelist, starting with a baseline of known findings that shrinks to zero.

For each fixed endpoint I would add parameterised tests that send quotes, UNION and time-delay payloads against a Testcontainers database and assert we never get extra rows or a SQL error. And I would run the whole thing with the security team: prioritise internet-facing unauthenticated endpoints, report progress in numbers, and have them retest.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Official documentation
java.sql, package documentation
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "You inherit 200 MyBatis XML mapper files where many queries use ${} for filters and sort...": https://scrivio-interview-library.netlify.app/databases/jdbc/95928dee6d/