Scrivio Interview library
ScenarioIntermediate6 min read · updated 12 November 2026

List places where SQL injection appears even in a codebase that uses JPA and PreparedStatement everywhere, and how you would find them in a review of a large Java service.

Even with JPA and PreparedStatement everywhere, injection hides wherever a query string is assembled from data: concatenated JPQL or HQL, native queries with formatted identifiers, Criteria code that passes input into function names, mapper syntax that inserts raw text, stored procedures that build dynamic SQL, and batch or report jobs that concatenate values read back from the database. In a large review we find them by searching for query-building patterns, running static analysis in CI, and watching database logs for odd statements.

Background to this question

Once a codebase has a rule like use JPA or PreparedStatement, people stop looking for SQL injection, and that is exactly when it survives in the corners. A senior engineer is expected to know where those corners are and to have a method for finding them in hundreds of thousands of lines without reading every file. In this answer, we will recap why parameterised APIs are not a full guarantee, walk through the places injection hides in a Java service and in the database itself, and then build a practical review method from grep to static analysis to database logs.

1A Quick Recap: Where Safety Actually Comes From

Safety does not come from the API name. It comes from one property: user-controlled data reaches the database only as a bound value, never as part of the statement text. createQuery, createNativeQuery, JdbcTemplate and even PreparedStatement all accept a string, and if that string was built with + or String.format from input, the API happily parses the attacker's text as part of the query. So in a review we are not looking for a missing PreparedStatement, we are looking for any place where a query string is assembled from something other than constants.

2Concatenated JPQL, HQL and Native Queries

The most common case is JPQL or HQL built by concatenation, usually in a search method with optional filters. JPQL injection cannot always run arbitrary SQL, but it can read other entities through subqueries and change the logic of the WHERE clause, which is enough to leak data.

Java
// injectable: status comes from the request
em.createQuery("SELECT o FROM Order o WHERE o.status = '" + status + "'", Order.class);
// status = x' OR '1'='1 -> every order of every customer
// injectable: identifier formatted into native SQL
em.createNativeQuery(String.format("SELECT * FROM %s WHERE id = :id", tableName));
// injectable: function name from input in the Criteria API
cb.function(request.getParameter("fn"), String.class, root.get("name"));
// safe: the value is a named parameter
em.createQuery("SELECT o FROM Order o WHERE o.status = :s", Order.class).setParameter("s", status);

The Criteria API is usually safe because values become parameters, but a few methods take names rather than values, such as function names and, in some code, raw SQL fragments passed through provider extensions. Passing request data into those is as dangerous as concatenation. Native queries most often go wrong with identifiers such as table names for partitions or tenants, which cannot be parameters and need an allow-list.

3Raw Text in Mappers and SQL Builders

Other data access tools have their own escape hatches. In MyBatis, #{name} becomes a bind parameter while ${name} pastes the raw text into the statement, so a single dollar sign in a mapper XML file is an injection point if the value comes from a user. jOOQ is safe with its typed DSL, but its plain SQL methods, which accept SQL strings, are not when the string is concatenated. Hibernate annotations such as @Formula and @SQLRestriction (formerly @Where) take SQL fragments; their values are compile-time constants, so input cannot reach them directly, but we should still check fragments that are assembled from configuration or properties. The same applies to admin consoles, report generators and logging or export tools that build SQL themselves.

4Injection Inside the Database: Procedures and Second-Order Attacks

Stored procedures look safe from Java because we call them with bound parameters. But a procedure that builds a statement inside itself with string concatenation and runs it with EXECUTE (PostgreSQL PL/pgSQL) or PREPARE (MySQL) reintroduces the problem one layer deeper.

SQL
-- injectable PL/pgSQL
EXECUTE 'SELECT count(*) FROM orders WHERE region = ''' || p_region || '''';
-- safe: identifiers with %I, values passed with USING
EXECUTE format('SELECT count(*) FROM %I WHERE region = $1', p_table) USING p_region;
Where injection hides in a parameterised codebase
PlaceWhat goes wrongHow to find it
JPQL or HQL with +input changes query logicgrep createQuery( with + or format
Native query identifierstable or column from inputgrep createNativeQuery, %s in SQL
Criteria function namesinput used as a namereview cb.function and raw fragments
MyBatis ${}raw text pasted into SQLgrep \$\{ in mapper files
Dynamic SQL in proceduresEXECUTE with concatenationsearch procedure source for EXECUTE
Batch and report jobsstored values concatenated laterstatic analysis taint from DB reads

A second-order attack is subtler. The application stores a value safely, for example a customer name O'Brien'); DROP ..., using a bound parameter, so nothing happens at write time. Weeks later a nightly batch job or report generator reads that name back and concatenates it into another query, trusting it because it came from our own database. The attack runs then. The lesson is that data from the database is still untrusted input when it is used to build SQL.

5A Review Method for a Large Service

Reading every file of a large service is not realistic, so we work from the cheapest wide search to the most precise check. First, a text search for the patterns that build queries: createQuery( or createNativeQuery( on the same line as + or String.format, StringBuilder variables whose names contain sql or query, ${ in MyBatis mappers, and EXECUTE in database migration files that define procedures. This finds most candidates in an hour.

Second, static analysis with taint tracking, which follows data from sources such as request parameters or database reads to sinks such as createQuery. Semgrep rules, SpotBugs with the Find Security Bugs plugin, or CodeQL can all do this; we run them in CI so new findings block merges, and we triage the existing ones once. Third, runtime evidence: database logs of syntax errors (in PostgreSQL, log_min_error_statement shows the failing statement) and statement statistics such as pg_stat_statements often reveal statements that only a manipulated input could produce. Finally, a short manual review of the data access layer around each finding, because the fix is usually a pattern, such as an allow-list or a query builder, that should be applied across similar code.

Step throughReviewing a large service for hidden injection
  1. Text searchcreateQuery with +, format, ${, EXECUTE
  2. Static analysis with taintrequest and DB reads to query sinks
  3. Runtime evidencesyntax errors, unusual statements in logs
  4. Confirm and fix patternallow-list, bind, format with %I
  5. Guard in CIblock new high-confidence findings

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

6Follow-up questions

Is JPQL injection really dangerous if it cannot run arbitrary SQL?

Yes. It can change the WHERE logic to return other users' data, use subqueries to read other entities, and sometimes reach database functions. That is usually enough for a data breach, so we treat it exactly like SQL injection.

How do you prioritise hundreds of static analysis findings?

By reachability and data. Findings where a request parameter reaches a query sink in an internet-facing endpoint come first, then internal endpoints and batch jobs on sensitive tables, and last those where the input is a constant or an enum. Confirming and fixing the top group quickly also teaches the team the patterns.

What should replace dynamic JPQL for search screens?

The Criteria API or Spring Data Specifications, Querydsl or jOOQ's typed DSL, which build queries from objects and bind every value. For sort and filter fields chosen by the client, an allow-list maps public names to entity attributes.

7Conclusion

In this answer, we saw that safety comes from keeping input out of the statement text, not from using JPA or PreparedStatement by name. Injection hides in concatenated JPQL and native queries, function names in Criteria code, MyBatis ${} and plain SQL builders, dynamic SQL inside stored procedures, and second-order attacks where stored values are later concatenated by batch or report jobs. We find them with targeted text search, taint-tracking static analysis in CI, database logs, and a focused manual review that fixes the pattern, not just the line.

What to say in the interviewAbout 80 seconds aloud

Open with

Using JPA and PreparedStatement does not make a codebase safe by itself; what matters is that input never becomes part of the query text, and every one of those APIs accepts a string.

Then, if they want more

So the places I look at are: JPQL or HQL built with concatenation, typically in search methods; native queries where a table or column name is formatted in, because identifiers cannot be parameters; Criteria code that passes request data into names, like cb.function; MyBatis dollar-brace placeholders and the plain SQL methods of tools like jOOQ; and anything that builds SQL from configuration, such as Hibernate fragments assembled from properties or report tools.

Inside the database, stored procedures that build SQL with EXECUTE or PREPARE and concatenation are injectable even when Java binds parameters, and second-order injection happens when a value stored safely is later concatenated by a batch job or report.

To find them in a large service, I start with a text search for createQuery or createNativeQuery next to plus or String.format, dollar braces in mappers and EXECUTE in procedure code. Then I run taint-tracking static analysis, like Semgrep, Find Security Bugs or CodeQL, in CI, and look at database logs for syntax errors and unusual statements. Each confirmed case gets a pattern fix across the codebase.

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.
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 "List places where SQL injection appears even in a codebase that uses JPA and...": https://scrivio-interview-library.netlify.app/databases/database-security/4c3f3af89d/