Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
193 views
in Technique[技术] by (71.8m points)

java - NamedParameterJdbcTemplate vs JdbcTemplate

I'm a beginner to Spring3.x , I'm learning Spring DAO support. I want to know the difference between NamedParameterJdbcTemplate and JdbcTemplate. Which one is the best by means of performance. And when to go for NamedParameterJdbcTemplate and when to go for JdbcTemplate.

question from:https://stackoverflow.com/questions/16359316/namedparameterjdbctemplate-vs-jdbctemplate

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...