Spring 专题
专题目录
您的位置:java > Spring专题 > Spring SimpleJdbcTemplate类命名参数实例
Spring SimpleJdbcTemplate类命名参数实例
作者:--    发布时间:2019-11-20
在jdbctemplate,这些sql参数通过一个特殊的占位符“?”符号表示,并通过位置绑定。现在的问题是,每当参数的顺序发生了变化,你必须也要改变参数绑定,这是容易出错,繁琐的维护。

为了解决这个问题,可以使用“命名参数”,sql参数是由一个冒号开始后续定义的名称,而不是位置。在另外的,命名参数只是在simplejdbctemplate类和namedparameterjdbctemplate支持。

请参见下面的三个例子用来使用命名参数在spring。

示例1

例子向您展示如何使用命名参数在一个 insert 语句。
//insert with named parameter
	public void insertnamedparameter(customer customer){
			
		string sql = "insert into customer " +
			"(cust_id, name, age) values (:custid, :name, :age)";
			
		map<string, object> parameters = new hashmap<string, object>();
		parameters.put("custid", customer.getcustid());
		parameters.put("name", customer.getname());
		parameters.put("age", customer.getage());
			
		getsimplejdbctemplate().update(sql, parameters);
				
	}

示例 2

例子来说明如何使用命名参数在批处理操作语句。
public void insertbatchnamedparameter(final list<customer> customers){
			
		string sql = "insert into customer " +
		"(cust_id, name, age) values (:custid, :name, :age)";
				
		list<sqlparametersource> parameters = new arraylist<sqlparametersource>();
		for (customer cust : customers) {
			parameters.add(new beanpropertysqlparametersource(cust)); 
		}
		
		getsimplejdbctemplate().batchupdate(sql,
			parameters.toarray(new sqlparametersource[0]));
	}

示例 3

另一个例子,在一个批处理操作语句中使用命名参数。
public void insertbatchnamedparameter2(final list<customer> customers){
			
	   sqlparametersource[] params = 
		sqlparametersourceutils.createbatch(customers.toarray());
		
	   getsimplejdbctemplate().batchupdate(
		"insert into customer (cust_id, name, age) values (:custid, :name, :age)",
		params);
		
	}

下载源代码 – http://pan.baidu.com/s/1hqprzju

网站声明:
本站部分内容来自网络,如您发现本站内容
侵害到您的利益,请联系本站管理员处理。
联系站长
373515719@qq.com
关于本站:
编程参考手册