NamedParameterJdbcTemplate vs JdbcTemplate NamedParameterJdbcTemplate vs JdbcTemplate java java

NamedParameterJdbcTemplate vs JdbcTemplate


When you use JdbcTemplate you give it SQL that has a ? placeholder for each parameter you want substituted into the SQL. When you assign parameters in the code you have to pass in arguments in an array and they get used in the order in which they appear in the array, like this:

Object[] args = new Object[] {"x", "y"};String sql = "select * from foo where a = ? and b = ?";jdbcTemplate.query(sql, args, resultSetExtractor);

so the SQL that gets run is select * from foo where a = 'x' and b = 'y'.

NamedParameterJdbcTemplate allows you to assign names to the parameter placeholders and pass in a map so the template can match the map names to the placeholders. So your code would look like:

String sql = "select * from foo where a = :mya and b = :myb";Map<String, Object> argMap = new HashMap<String, Object>();argMap.put("mya", "x");argMap.put("myb", "y");namedParameterJdbcTemplate.query(sql, argMap, resultSetExtractor);

generating the same SQL as the first example.

Running the query is the time-intensive part, the performance of the argument insertion is a non-issue.

The idea is that matching the arguments by name is less error-prone than having to specify them in a particular order. In real-life applications I've worked on, typically we store the SQL in a separate file from the DAO code, and it may be easy to accidentally get the parameters in the wrong order.


There's no measurable difference performance. The NamedParameterJdbcTemplate is a convenience that allows you to use named parameters.If you're really curious take a look at the source code which is readily available for download.I find that reading the source code gives me more confidence in the answers I get on the forums.