Skip to content
javahacks.dev
Hibernate

How to Prevent SQL Injection in Java With JDBC and JPA

Stop SQL injection in Java by binding values with parameters in JDBC, JPA and Spring, allow-listing identifiers and limiting what the database account can do.

8 min read
Summarize in AI
Flat illustration of an application reaching a database through a JDBC driver, with the OpenJDK, Hibernate, Spring Security, Flyway and PostgreSQL logos.

SQL injection has been the top web vulnerability for over twenty years, and it is also one of the simplest to prevent: never build a query by pasting user input into the SQL text. A bound parameter travels to the database separately from the statement, so the database can never confuse data with code. The vulnerability persists because it is easy to write by accident, with string concatenation that works in every test and a LIKE clause or a dynamic ORDER BY that parameters cannot express. This post shows the vulnerable shape and a working attack, the fix in plain JDBC, the fix in Spring's JdbcClient, how JPA and Hibernate fall into and avoid the same trap, the places parameters cannot reach and how to handle them with allowlists, LIKE wildcards, defense in depth and a way to find the holes in an existing codebase. Examples use Java 25, PostgreSQL 17 and Spring Boot 4.

The vulnerable shape

A login check or a search that concatenates a request value into a query:

src/main/java/dev/javahacks/users/UserDao.javajava
public Optional<User> findByEmail(String email) throws SQLException {
    String sql = "select id, email, role from users where email = '" + email + "'";
    try (Connection c = dataSource.getConnection();
         Statement st = c.createStatement();
         ResultSet rs = st.executeQuery(sql)) {
        return rs.next() ? Optional.of(map(rs)) : Optional.empty();
    }
}

With a normal value the query is what you intended. With a crafted one the structure of the statement changes. Print what the code builds for two inputs:

java
String normal = "[email protected]";
String attack = "x' OR '1'='1";
System.out.println("select id, email, role from users where email = '" + normal + "'");
System.out.println("select id, email, role from users where email = '" + attack + "'");
Text
select id, email, role from users where email = '[email protected]'
select id, email, role from users where email = 'x' OR '1'='1'

The second statement is a different query. The quote in the input closed the string, OR '1'='1' is always true, and the where clause now matches every row, so rs.next() returns the first user in the table, which is often an administrator. The same shape lets an attacker append ; drop table users; -- where the driver allows multiple statements, or use UNION SELECT to read other tables. This is not hypothetical: it is how breaches have happened for decades, and it is category A03 (injection) in the OWASP Top 10. The root cause is that the program mixed code and data in one string.

JDBC: PreparedStatement

A PreparedStatement sends the SQL text with placeholders first and the values separately. The database parses the statement before it sees any value, so a value can only ever be data:

java
public Optional<User> findByEmail(String email) throws SQLException {
    String sql = "select id, email, role from users where email = ?";
    try (Connection c = dataSource.getConnection();
         PreparedStatement ps = c.prepareStatement(sql)) {
        ps.setString(1, email);
        try (ResultSet rs = ps.executeQuery()) {
            return rs.next() ? Optional.of(map(rs)) : Optional.empty();
        }
    }
}

The attack string is now compared literally against the email column and matches nothing:

Text
select id, email, role from users where email = ?     -- parameter 1: x' OR '1'='1
(0 rows)

setString, setLong, setObject and the other setters handle quoting and type conversion for you. Rules that go with it: the SQL string must be a constant (or built only from constants), never from input; use one ? per value; do not wrap a placeholder in quotes ('?' is a literal question mark). The differences between Statement, PreparedStatement and CallableStatement are explained in JDBC PreparedStatement versus Statement, and the API is in the Oracle JDBC tutorial.

Spring: JdbcClient and JdbcTemplate

Spring's helpers are parameterized by design. JdbcClient takes named parameters, which are clearer than positions:

src/main/java/dev/javahacks/users/UserRepository.javajava
@Repository
class UserRepository {

    private final JdbcClient jdbc;

    UserRepository(JdbcClient jdbc) {
        this.jdbc = jdbc;
    }

    Optional<User> findByEmail(String email) {
        return jdbc.sql("select id, email, role from users where email = :email")
                .param("email", email)
                .query(User.class)
                .optional();
    }

    List<User> findByRoles(List<String> roles) {
        return jdbc.sql("select id, email, role from users where role in (:roles)")
                .param("roles", roles)           // expands to ?, ?, ? safely
                .query(User.class)
                .list();
    }
}

The list case is where people fall back to concatenation, building in ('a','b') with a loop. Do not: the named parameter expands to one placeholder per element. JdbcTemplate works the same with ? placeholders, as does NamedParameterJdbcTemplate. The one thing to avoid is jdbcTemplate.query("select ... where x = '" + v + "'", ...), which compiles and executes without complaint. A trailing note from the unique-key side: errors from bad data surface as constraint exceptions, not injection; see SQLIntegrityConstraintViolationException on insert.

JPA and Hibernate

JPA does not make injection impossible; it makes the safe form the easy one, and offers the unsafe one just as easily. Safe:

java
@Query("select u from User u where u.email = :email")
Optional<User> findByEmail(@Param("email") String email);

// or derived from the method name; parameters are always bound
Optional<User> findByEmailIgnoreCase(String email);

// or with the entity manager
em.createQuery("select u from User u where u.email = :email", User.class)
  .setParameter("email", email)
  .getSingleResultOrNull();

Unsafe, and common in code that grew:

java
// Concatenated JPQL: injectable
em.createQuery("select u from User u where u.email = '" + email + "'", User.class).getResultList();

// Concatenated native SQL: injectable
em.createNativeQuery("select * from users where email = '" + email + "'", User.class).getResultList();

// SpEL in @Query with raw input is also an injection route when misused

The criteria API and Spring Data's derived queries bind parameters internally. The risk lives in any string you assemble yourself: JPQL, HQL, native SQL and @Query text. A useful review heuristic: inside a query string, every + is suspect.

What parameters cannot cover

A placeholder stands for a value. It cannot stand for a table name, a column name, a sort direction or a keyword, because those are part of the statement's structure. The temptation is to concatenate, and the fix is an allowlist: map the user's choice to a constant you wrote.

java
private static final Map<String, String> SORTABLE = Map.of(
        "email", "email",
        "created", "created_at",
        "role", "role");

List<User> list(String sortBy, String direction) {
    String column = SORTABLE.getOrDefault(sortBy, "created_at");
    String dir = "desc".equalsIgnoreCase(direction) ? "desc" : "asc";
    return jdbc.sql("select id, email, role from users order by " + column + " " + dir)
            .query(User.class).list();
}

Every part of the final string either is a constant or came out of a lookup in a table you control. An unknown sortBy falls back to the default, never to the raw input. Do the same for table or column choice. With Spring Data, accept a Pageable but validate each Sort property against a whitelist before passing it on, since the framework turns property names into JPQL. Never try to "escape" a name with a regular expression; an allowlist is simpler and cannot be forgotten in one code path.

LIKE and wildcards

A bound parameter in a LIKE is safe from injection but not from surprise: the user's % and _ are still wildcards, so a search for % returns every row, which is a cheap way to dump a table or force a full scan. Escape them and declare the escape character:

java
static String escapeLike(String s) {
    return s.replace("!", "!!").replace("%", "!%").replace("_", "!_");
}

jdbc.sql("select id, email, role from users where email like :q escape '!'")
    .param("q", "%" + escapeLike(term) + "%")
    .query(User.class).list();

Add a minimum term length and a limit on results, both to protect the database and to stop enumeration.

Defense in depth

Parameters are the primary defense; add layers so one mistake is not a breach.

  • Least privilege. The application's database user needs SELECT, INSERT, UPDATE, DELETE on its own tables, not DROP, not superuser, not access to other schemas. If an injection slips through, the damage is bounded.
  • Separate users per purpose. A read-only user for reporting endpoints.
  • No detailed errors to clients. A SQL error with the statement text helps an attacker map the schema. Return a generic message and log the details, as in problem details responses.
  • Validate input shape. An id is a number; a state is one of an enum. Validation at the boundary rejects most hostile strings before they reach a query.
  • Disable stacked statements where the driver or engine allows it, and keep the database patched.
  • WAF rules can reduce noise, but they are not a fix and are bypassed routinely.

The broader practice is in Java security basics for backend developers, and the reference checklist is the OWASP SQL Injection Prevention Cheat Sheet.

Find the holes

Review an existing codebase mechanically first, then by reading.

Shell
grep -rnE '(createStatement|executeQuery|executeUpdate|createNativeQuery|createQuery|jdbcTemplate\.(query|update)|\.sql\()\s*\(?\s*".*"\s*\+' src/main/java
Text
src/main/java/dev/javahacks/users/UserDao.java:14:    ... st.executeQuery("select ... where email = '" + email + "'")

Any hit is a string-built query. Add a static analysis rule to CI that flags them (SpotBugs with the Find Security Bugs plugin has SQL_INJECTION_JDBC and SQL_INJECTION_JPA, and CodeQL has an equivalent query), so the next one fails the build. A test that submits the classic payloads to every endpoint and asserts no extra rows and no 500 is cheap insurance:

java
@ParameterizedTest
@ValueSource(strings = {"x' OR '1'='1", "'; drop table users; --", "\" OR \"\"=\""})
void rejectsInjectionStrings(String payload) throws Exception {
    mvc.perform(get("/users").param("email", payload))
       .andExpect(status().isNotFound());
}

Where this does not apply

A query that contains no input, a fixed report or a health check, has nothing to inject. A stored procedure call with bound parameters is as safe as a prepared statement, but a procedure that builds dynamic SQL inside with concatenation moves the bug into the database. NoSQL stores have their own injection forms (a JSON operator smuggled into a query document) that these rules do not cover, though the principle of keeping data out of the query structure is the same. And an ORM does not protect you from the strings you assemble yourself.

Also inSecurity
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.