Does Spring JDBC provide any protection from SQL injection attacks?

brabster picture brabster · Aug 31, 2011 · Viewed 27.2k times · Source

Spring's JdbcTemplate abstraction provides a lot of functionality, but can it be used in such a way that provides protection from SQL injection attacks?

For example, like the kind of protection you would get using PreparedStatement with properly defined parameterization.

Answer

Donal Fellows picture Donal Fellows · Aug 31, 2011

It most certainly does. This example is straight from the Spring 3.0 docs (but is the same in 2.*):

String lastName = this.jdbcTemplate.queryForObject( 
        "select last_name from t_actor where id = ?", 
        String.class, 1212L); 

As you can see, it strongly favors prepared statements (which it must be using behind the scenes for you): you specify the parameters with placeholders (?) and supply an array of objects to fill into the parameters. (The last parameter is the type of the expected result, but that's not very relevant for this question.)

You can also use a NamedParameterJdbcTemplate and supply the parameters in a Map, which is perhaps less efficient but definitely more mnemonic.