2017  Kodetalk | Feedback | Privacy Policy | Terms | About
userimage

Difference between NamedParameterJdbcTemplate and JdbcTemplate in Spring 3.x

I am learning Spring DAO and got confusion WRT NamedParameterJdbcTemplate and JdbcTemplate like,

  • Which one is the best by means of performance.
  • And when to go for NamedParameterJdbcTemplate and when to go for JdbcTemplate

And if any additional information will be provided here its better for me to understand

userimage

SimpleJdbcTemplate and NamedParameterJdbcTemplate both contain a JdbcTemplate and delegate to it. So in fact in such a DAO you would only have one JdbcTemplate.

Also, JdbcTemplate objects have very little state, and are thread-safe. There is very little implact to creating multiple objects.


If you go for JdbcTemplate then you need to 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);


And if you go for NamedParameterJdbcTemplate then you need to assign names to the parameter placeholders and pass in a map so the template can match the map names to the placeholders, like this:


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);


The idea is that matching the arguments by name is less error-prone than having to specify them in a particular order. In a real-life application typically SQL is stored in a separate file from the DAO code, and getting the parameters in the right order can be painful.

Answer is