Scrivio Interview library
DebuggingFoundations6 min read · updated 12 November 2026

Find the vulnerability in this repository method and fix it:

Java
List<Order> find(String name, String sortField) {
return em.createQuery("select o from Order o where o.customer = '" + name + "' order by o." + sortField, Order.class).getResultList();
}

The method concatenates both name and sortField into the JPQL string, so it is injectable even though it is JPQL and not SQL: a crafted name can change the WHERE clause, and sortField can add arbitrary query text. The fix is to bind the value with a named parameter, where o.customer = :name with setParameter("name", name), and, because ORDER BY columns cannot be parameters, to validate sortField against an allowlist of fields. Spring Data's Sort validates property names for derived queries, JpaSort.unsafe skips that check, and native queries need the same care.

Why this question is asked

Many developers believe that JPA protects them from SQL injection automatically. It does, but only when values are bound as parameters; concatenating strings into JPQL is just as dangerous as concatenating them into SQL. This kind of method is common in older repositories, and the sort field is the part that even careful developers often get wrong. Interviewers use it as a code-reading exercise to see whether we spot both problems and know that the two need different fixes. In this answer, we will recap how injection works, show both attacks on this method, fix the value with a bound parameter, fix the sort field with an allowlist, look at how Spring Data handles sorting, and cover native queries.

1A Quick Recap of Injection

Injection happens when user input becomes part of the query text instead of being treated as a value. The database, or in this case Hibernate's JPQL parser, cannot tell which parts of the string the developer wrote and which parts came from the user, so input containing quotes or keywords changes the query's meaning.

JPQL (Jakarta Persistence Query Language) is translated by Hibernate into SQL. That translation does not clean the input; it faithfully translates whatever JPQL it receives, including the attacker's additions. So JPQL injection is real, and it can read or affect any data that the entity model reaches.

2Reproducing the Two Attacks

Here is the method again, with what happens for crafted inputs.

Java
List<Order> find(String name, String sortField) {
return em.createQuery("select o from Order o where o.customer = '" + name +
"' order by o." + sortField, Order.class).getResultList();
}
find("alice", "createdAt");
// select o from Order o where o.customer = 'alice' order by o.createdAt -> Alice's orders
find("x' or '1'='1", "createdAt");
// select o from Order o where o.customer = 'x' or '1'='1' order by o.createdAt -> every customer's orders
find("alice", "id, (select max(u.passwordHash) from User u)");
// order by o.id, (subquery) -> may parse, depending on the Hibernate version and dialect

Notice that the first attack does not need SQL knowledge at all: one quote closes the string and the rest becomes a condition that is always true. The second attack shows that the sort field is a separate injection point: whatever follows order by o. becomes query text. Even when a specific payload is rejected by the parser, an attacker can use differences in error messages or timing to learn about the data, so "it threw an exception" is not a defence.

3Fix 1: Bind the Value as a Parameter

Values belong in parameters. With a named parameter, the query text is fixed and the value is sent separately; Hibernate turns it into a JDBC bind parameter, and the database treats it strictly as data. A quote in the name is just a character in the name.

Java
em.createQuery("select o from Order o where o.customer = :name", Order.class)
.setParameter("name", name)
.getResultList();
// name = "x' or '1'='1" -> looks for a customer literally named x' or '1'='1 -> empty list

4Fix 2: Allowlist the Sort Field

Parameters only work for values. Column names, sort directions and other identifiers are part of the query's structure, and neither JDBC nor JPQL lets us bind them: order by :field would sort by a constant string, not by a column. So for sortField we do not try to escape it; we check it against a fixed list of allowed properties and map each to a known path.

Java
private static final Map<String, String> SORTABLE = Map.of(
"date", "o.createdAt",
"total", "o.total",
"status", "o.status");
List<Order> find(String name, String sortField) {
String orderBy = SORTABLE.get(sortField);
if (orderBy == null) throw new IllegalArgumentException("Unsupported sort: " + sortField);
return em.createQuery("select o from Order o where o.customer = :name order by " + orderBy,
Order.class)
.setParameter("name", name)
.getResultList();
}
// find("alice", "total") -> order by o.total
// find("alice", "id, (select ...)") -> IllegalArgumentException, nothing reaches Hibernate
What can be a parameter
Query partExampleSafe approach
Value in WHEREo.customer = 'alice'Named parameter :name
Value in IN listo.status in (...)Collection parameter
Sort columnorder by o.totalAllowlist mapped to fixed paths
Sort directionasc / descMap to fixed strings
Table or entity namefrom OrderNever from user input

What changed is that the only strings concatenated into the query now come from our own map, never from the user. The user chooses a key, and the code chooses the text. Using public names such as date and total also decouples the API from entity field names, which is a small bonus. The same approach applies to sort direction: map asc and desc to fixed strings, never pass them through.

5How Spring Data Handles Sorting

If this repository were a Spring Data JPA repository, sorting would usually come from a Sort or Pageable parameter. For derived query methods, such as findByCustomer(String customer, Sort sort), Spring Data resolves each sort property against the entity's properties and rejects unknown ones, so Sort.by("id, (select ...)") fails instead of reaching the query. For @Query methods, Spring Data also checks that sort expressions are plain property references or aliases.

JpaSort.unsafe(...) exists for the cases where we deliberately sort by a function expression, and as its name says, it skips that validation. It must never receive user input directly. Even with Sort, an allowlist at the API layer is still worth having, because it stops users sorting by properties they should not see or that have no index.

6Native Queries Need the Same Care

Native SQL through createNativeQuery, @Query(nativeQuery = true) or JdbcTemplate follows the same rules: bind values with parameters, and allowlist identifiers. For queries whose shape really varies, with optional filters and sorts, the Criteria API or Spring Data Specifications build the query from objects instead of strings, so values are always bound and paths are always real properties. Code review should treat any + inside a query string as a finding until proven safe.

7Follow-up questions

Is JPQL injection less dangerous than SQL injection?

Somewhat narrower, because JPQL works on mapped entities and cannot run arbitrary SQL statements such as dropping a table. But it can still read any entity the model reaches, bypass filters, and in some setups reach database functions. Treat it as a real vulnerability.

Can I escape quotes in name instead of using a parameter?

Escaping by hand is fragile: it depends on the database, the encoding and edge cases like backslashes. Parameters avoid the problem completely and also let the database reuse query plans.

Would Hibernate's query validation stop the sort attack?

Sometimes a payload fails to parse, but that depends on the payload and the version, and errors can still leak information. Validation by an allowlist is the only fix that does not depend on the parser's behaviour.

8Conclusion

In this answer, we found two injection points in one JPQL query. The customer name is a value, so we bind it with a named parameter and setParameter. The sort field is part of the query structure, which cannot be a parameter, so we validate it against an allowlist that maps user choices to fixed paths. Spring Data's Sort validates property names unless JpaSort.unsafe is used, and native queries need the same parameters, allowlists, or Criteria and Specifications.

What to say in the interviewAbout 90 seconds aloud

Open with

This method has two injection points, and the fact that it is JPQL does not help, because Hibernate translates whatever JPQL string it is given. The first is name.

Then, if they want more

It is concatenated inside quotes, so a value like x quote or quote one equals one closes the string and turns the condition into something always true, and the query returns every customer's orders. The fix is a named parameter: where o.customer equals colon name, and setParameter name.

The value then goes to the database as a bind parameter and is treated purely as data. The second is sortField, which is appended after order by o dot. Anything there becomes query text, including expressions and subqueries. Parameters cannot help here, because ORDER BY columns are part of the query structure and cannot be bound.

So I would validate sortField against an allowlist, ideally a map from public names like date or total to fixed paths like o.createdAt, and reject anything else before building the query. Direction gets the same treatment.

If this were a Spring Data repository, I would use Sort or Pageable: for derived queries, Spring Data checks sort properties against the entity, while JpaSort.unsafe skips that check and must never get user input. And the same rules apply to native queries and JdbcTemplate: bind values, allowlist identifiers, or use Criteria or Specifications for dynamic queries.

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
OWASP Top Ten
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 "Find the vulnerability in this repository method and fix it:": https://scrivio-interview-library.netlify.app/spring-boot/web-security-threats/fc1060529d/