How does Hibernate handle SQL Injection?

Hibernate guards against SQL injection primarily by using parameterized (prepared) statements under the hood, so user-supplied values are always bound as parameters rather than concatenated directly into SQL text.

Key Points: • HQL and the Criteria API compile queries into parameterized SQL automatically, keeping bound values separate from query structure. • Named and positional parameters (setParameter()) ensure input values are treated strictly as data, never as executable SQL. • The risk reappears if a developer manually concatenates user input into HQL or native SQL strings instead of using parameter binding. • Native SQL queries via createNativeQuery() should still use bind parameters rather than string concatenation to stay safe. • Because prepared statements handle escaping at the JDBC driver level, injection attempts embedded in a parameter value are treated as literal data, not code.

Example: Writing session.createQuery("from User where username = :name").setParameter("name", userInput) is safe because userInput is bound as a parameter, whereas building the string "from User where username = '" + userInput + "'" would reopen the door to injection.

Code Example:

// Safe - parameterized
Query query = session.createQuery("from User where username = :name");
query.setParameter("name", userInput);

// Unsafe - string concatenation, avoid this
String hql = "from User where username = '" + userInput + "'";

Interview Tip: A concise interview answer is:

"Hibernate protects against SQL injection because HQL, Criteria queries, and parameter binding all compile down to prepared statements, so input values are bound as data rather than concatenated into the SQL text. The risk only comes back if a developer manually builds query strings with raw user input instead of using bind parameters."