SQL Injection with JPA and Hibernate
Fast recall
Quick revision
Core answer
Whether you know ORMs aren't magically injection-proof.
Assuming JPA/Hibernate prevents injection regardless of how queries are built.
Distinguish bound parameters (safe) from string-concatenated JPQL/native (vulnerable).
Interview-ready guide
Interview answer
entityManager.createQuery("select u from User u where u.email = :email").setParameter("email", email) keeps the email as a value. Building "... where u.email = '" + email + "'" is unsafe even though the language is JPQL. The provider translates the already-compromised JPQL structure into SQL. Spring Data derived methods bind their arguments, while a dynamically assembled @Query/native fragment needs the same review as raw JDBC.
SQL Injection with JPA and Hibernate
Direct Answer
JPA and Hibernate are safe only when values are bound as parameters or expressed through safe Criteria operations. Concatenating untrusted input into JPQL/HQL or a native SQL string can change query structure and is injectable. Entity mapping does not sanitize query text, and CriteriaBuilder is safe only while untrusted text remains values rather than raw expressions/fragments.
Common Mistakes & Pitfalls
- Assuming the ORM is inherently safe regardless of query construction.
- Concatenating into JPQL/HQL — injectable like raw SQL.
- Concatenating into native queries — highest risk; always bind.
- Dynamic identifiers via string-building — allow-list them, same as JDBC.
Check your understanding
Answer these without looking back at the article.
- What is SQL injection and how does it work?
- How does PreparedStatement prevent SQL injection in JDBC?
- What are other SQL injection prevention techniques besides PreparedStatement?
Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.