NamedParameterJdbcTemplate 与 JdbcTemplate [英] NamedParameterJdbcTemplate vs JdbcTemplate

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

问题描述

我是 Spring3.x 的初学者,我正在学习 Spring DAO 支持.我想知道 NamedParameterJdbcTemplateJdbcTemplate 之间的区别.就性能而言,哪一个是最好的.什么时候使用 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.

推荐答案

当你使用 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 where a = 'x' and b = 'y'.

so the SQL that gets run is select * from foo where a = 'x' and 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.

运行查询是耗时的部分,参数插入的性能不是问题.

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 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.

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

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