Video in progress

How should you pass a value into a JPQL query, and why is concatenating a string dangerous?

Pass values as parameters: named (:name) or positional (?1). If you build the string with +, you open the door to SQL (JPQL) injection, and a new query plan gets built for every different value.

📖 Answer

Dangerous:

String q = "select u from User u where u.login = '" + login + "'";
em.createQuery(q, User.class).getResultList();

If login comes in as x' or '1'='1, the query returns every user. JPQL is not protected against injection either, because in the end it becomes SQL.

The right way:

em.createQuery("select u from User u where u.login = :login", User.class)
  .setParameter("login", login)
  .getResultList();

In Spring Data:

@Query("select u from User u where u.login = :login")
Optional<User> findByLogin(@Param("login") String login);

With parameters the database gets a PreparedStatement: the value is never interpreted as part of the query text, and Hibernate parses the query once and keeps it in a cache.

Some things can't be parameters, such as a table name or an order by column. If you take those from the user, check them against a predefined list of allowed values.