Quick revision
The short answer
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.
What to remember
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.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
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.
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.
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.
| Query part | Example | Safe approach |
|---|---|---|
| Value in WHERE | o.customer = 'alice' | Named parameter :name |
| Value in IN list | o.status in (...) | Collection parameter |
| Sort column | order by o.total | Allowlist mapped to fixed paths |
| Sort direction | asc / desc | Map to fixed strings |
| Table or entity name | from Order | Never 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.
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/