3

I'm working with JPA. How could my application be SQL injection safe if I'm using a native sql query (not entity query)? I need to build the native sql query with the data submitted by a user from a html form.

If I use parameters in the native sql I can avoid SQL injection attacks, but my problem is that I can't be sure how many data fields are being submitted by the user.

Eduardo
  • 1,169
  • 5
  • 21
  • 56

1 Answers1

9

You should use positional parameters binding:

String queryString = "select * from EMP e where e.name = ?1";
Query query = em.createNativeQuery(queryString, Employee.class);
query.setParameter(1, "Mickey");

Please note that you should not use named parameters binding (:empName) in your query as JPA Spec says

Only positional parameter binding may be portably used for native queries.

This should secure you from SQL Injection attacks.

Maciej Dobrowolski
  • 11,561
  • 5
  • 45
  • 67
  • I'd be grateful for an explanation why ? is better than :myParameter and how it prevents the injection. – Zon Nov 13 '20 at 16:43
  • Do you mean positional vs named paramaters binding? It was about native queries - JPA Specification does not guarantee portability in this case – Maciej Dobrowolski Nov 13 '20 at 16:58