Spring Data JPA and SQL Injection Safety – Java Backend
Fast recall
Quick revision
Core answer
@Query parameters, but JPA does not make all query construction safe. Injection can return when custom repository code concatenates request data into JPQL or native SQL, or when untrusted text is accepted as query structure such as a column, function, or direction. Bind values and map structural choices from an allowlist or use Criteria/Specifications.Interview-ready guide
Interview answer
Spring Data JPA protects the common value-binding cases. A derived method such as findByEmail and an @Query using :email pass the email as a parameter, so quotes in the value do not become JPQL or SQL syntax.
JPA is not automatic protection for every query. A custom repository can still concatenate a request value into a string and pass it to EntityManager.createQuery or createNativeQuery. That recreates injection. A Java @Query annotation itself must be a compile-time constant, so runtime concatenation belongs in the custom query code, not inside the annotation example.
Values should always be bound. Dynamic structure such as a column, function, or sort direction should come from a fixed mapping or allowlist, or be built with Criteria API or Specifications. Normal native queries can use bound parameters too. APIs such as JpaSort.unsafe should receive only trusted, server-defined expressions.
Spring Data JPA and SQL Injection Safety – Java Backend
Direct Answer
Spring Data JPA safely binds values for derived query methods and @Query parameters, but JPA does not make all query construction safe. Injection can return when custom repository code concatenates request data into JPQL or native SQL, or when untrusted text is accepted as query structure such as a column, function, or direction. Bind values and map structural choices from an allowlist or use Criteria/Specifications.
Common Mistakes & Pitfalls
- Assuming ORM means immune: custom JPQL and native SQL can still concatenate attacker data.
- Using an impossible annotation example:
@Queryis a compile-time string; runtime concatenation normally occurs in custom repository code. - Treating identifiers like values: map requested columns, functions, and sort directions from a trusted set.
- Calling every native query vulnerable: a native query with bound values can be safe from value injection.
- Passing request text to intentionally unsafe sort APIs:
JpaSort.unsafeshould use only server-chosen expressions.
Check your understanding
Answer these without looking back at the article.
- How do you safely implement dynamic filtering where the columns vary at runtime?
- Is the Criteria API or Specifications safer than building a @Query string?
- Does using nativeQuery = true change anything about injection safety?
Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.