【實驗二】Spring框架筆記——NamedParameterJdbcTemplate與具名參數


 

在經典的 JDBC 用法中, SQL 參數是用占位符 ? 表示,並且受到位置的限制. 定位參數的問題在於, 一旦參數的順序發生變化, 就必須改變參數綁定. 

在 Spring JDBC 框架中, 綁定 SQL 參數的另一種選擇是使用具名參數(named parameter).

 

那么什么是具名參數?

具名參數: SQL 按名稱(以冒號開頭)而不是按位置進行指定. 具名參數更易於維護, 也提升了可讀性. 具名參數由框架類在運行時用占位符取代

具名參數只在 NamedParameterJdbcTemplate 中得到支持。

 

在 SQL 語句中使用具名參數時, 可以在一個 Map 中提供參數值, 參數名為鍵

也可以使用 SqlParameterSource 參數

批量更新時可以提供 Map 或 SqlParameterSource 的數組

 

現在,我們在上一篇博客文章的例子的基礎上,繼續編寫代碼:

我們在applicationContext.xml后面加入具名類對象的bean:

配置文件:

<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd"> <!-- 自動掃描的包 --> <context:component-scan base-package="com.happBKs.spring.jdbcSpring"></context:component-scan> <!-- 導入資源文件 --> <context:property-placeholder location="classpath:db.properties" /> <!-- 配置c3p0數據源 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="user" value="${jdbc.user}"></property> <property name="password" value="${jdbc.password}"></property> <property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property> <property name="driverClass" value="${jdbc.driverClass}"></property> <property name="initialPoolSize" value="${jdbc.initPoolSize}"></property> <property name="maxPoolSize" value="${jdbc.maxPoolSize}"></property> </bean> <!-- 配置jdbc模板類 --> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="dataSource"></property> </bean> <!-- 配置 NamedParameterJdbcTemplate,該對象可以使用具名參數。 但它沒有無參構造器,所以必須為其制定構造參數,這里指定的是出c3p0數據源 --> <bean id="namedParameterJdbcTemplate" class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate"> <constructor-arg ref="dataSource"></constructor-arg> </bean> </beans>

之后我們不再使用上次提到的EmployeeBean類,因為我們已經知道了Spring JDBC並不能提供像Hibernate等ORM框架那樣的類屬性的級聯映射,所以我們把屬性department改為了deptId。

package com.happBKs.spring.jdbcSpring; public class EmployeeBean2 { Integer id; String lastName; String email; Integer deptId; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public Integer getDeptId() { return deptId; } public void setDeptId(Integer deptId) { this.deptId = deptId; } public EmployeeBean2(Integer id, String lastName, String email, Integer deptId) { super(); this.id = id; this.lastName = lastName; this.email = email; this.deptId = deptId; } public EmployeeBean2() { super(); // TODO Auto-generated constructor stub } @Override public String toString() { return "EmployeeBean2 [id=" + id + ", lastName=" + lastName + ", email=" + email + ", deptId=" + deptId + "]"; } }

然后,我們來使用具名參數來完成我們之前提到的各種更新操作:

比如之前我們插入一個記錄的寫法是:

 

 

這種寫法,賦值的參數沒有給予具體的名稱,只通過占位符?來完成占位,通過賦值參數的順序來對應相應的參數。現在我們可以借助於org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate來幫助我們解決這個問題:

不過這里有兩種方法,我們先介紹最一般的一種:

/*  * 可以為參數取名字:ln,:email,:deptid  * 優點:如果有多個參數,不用去糾結於參數的位置順序,直接對應參數名,便於維護  * 缺點:較為麻煩  */ @Test public void testNamedParameterJdbcTemplate(){ //之前不適用具名參數的用法: //String sql="insert employee(last_name,email,dept_id) values(?,?,?)"; //我們給予參數賦值必須依賴於?的順序 // 使用具名參數的用法: String sql="insert employee(last_name,email,dept_id) values(:ln,:email,:deptid)"; Map<String,Object> paramMap=new HashMap<String, Object>(); paramMap.put("ln", "超級無敵銀河最強臨時工"); paramMap.put("email", "super@qq.com"); paramMap.put("deptid", 4); namedParameterJdbcTemplate.update(sql,paramMap); }

這里,SQL語句中的賦值參數被用":"的形式給出,這里就是具名參數。然后我們可以通過一個Map對象,Map的key是我們的具名參數,而value則是參數的值,然后通過NamedParameterJdbcTemplate類對象的方法update來完成曾刪改操作。

運行結果:

 

不過,這種方法還是有比較麻煩的地方,我們需要在map對象中逐一指定參數。

這時候,你可能不禁感慨,還是ORM框架好,類屬屬性能夠自動與數據庫表的字段映射。這里Spring JDBC在具名參數賦值時也考慮了類似的解決方法。

下面,我來介紹具名參數的第二種方法:

我們需要將具名參數定義為與類的屬性名稱一樣的名字,然后,可以創建一個相應的類的對象,並調用相應屬性的set方法賦值,之后,我們就調用update的另一個重載方法:

/*  * 使用具名參數時,可以使用int org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate.update(String sql, SqlParameterSource paramSource) throws DataAccessException 方法進行更新操作: 1. SQL語句中的具名參數與類的屬性名一致 2. 使用接口SqlParameterSource的BeanPropertySqlParameterSource實現類作為參數  */ @Test public void testNamedParameterJdbcTemplate2(){ //之前不適用具名參數的用法: //String sql="insert employee(last_name,email,dept_id) values(?,?,?)"; //我們給予參數賦值必須依賴於?的順序 // 使用具名參數的用法: String sql="insert employee(last_name,email,dept_id) values(:lastName,:email,:deptId)"; EmployeeBean2 e=new EmployeeBean2(); e.setLastName("haha"); e.setEmail("haha@qq.com"); e.setDeptId(4); SqlParameterSource sqlParameterSource=new BeanPropertySqlParameterSource(e); namedParameterJdbcTemplate.update(sql,sqlParameterSource); }

運行結果:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM