NamedParameterJdbcTemplate与JdbcTemplate [英] NamedParameterJdbcTemplate vs JdbcTemplate

查看:371
本文介绍了NamedParameterJdbcTemplate与JdbcTemplate的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Spring3.x的初学者,我正在学习Spring DAO支持。
我想知道NamedParameterJdbcTemplate和JdbcTemplate之间的区别。
通过表现,哪一个是最好的。什么时候去NamedParameterJdbcTemplate
以及何时去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. Your answer will help a lot to the beginners like me.

推荐答案

当你使用JdbcTemplate时,你给它的SQL是要替换为SQL的每个参数的占位符。当您在代码中分配参数时,您必须在数组中传递参数,并按照它们在数组中出现的顺序使用它们,如下所示:

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

所以运行的SQL是 select * from foo,其中a =' x'和b ='y'

NamedParameterJdbcTemplate允许您为参数占位符指定名称并传入地图,以便模板可以将地图名称与占位符匹配。所以你的代码看起来像:

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

生成与第一个示例相同的SQL(并且运行查询是时间密集型部分,参数插入的性能不是问题。

generating the same SQL as the first example (and running the query is the time-intensive part, the performance of the argument insertion is a non-issue.).

这个想法是,按名称匹配参数比不必按特定顺序指定它们更不容易出错。在实际应用程序中,SQL通常存储在与DAO代码不同的文件中,并且可能很容易意外地以错误的顺序获取参数。

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 it may be easy to accidentally get the parameters in the wrong order.

这篇关于NamedParameterJdbcTemplate与JdbcTemplate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆