1. 程式人生 > >Spring 在 JDBC 模板中使用具名引數

Spring 在 JDBC 模板中使用具名引數

Spring 的xml檔案配置內容有

<!-- Spring使用模板具名引數 -->
<!-- 具名模板使用的話,必須是有引數的建構函式 -->
<bean id="namedparam" class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate">
<constructor-arg ref="datasource"></constructor-arg>
</bean>

傳統的方式是這樣的

package cn.com.day03;
import java.util.HashMap;
import java.util.Map;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
public class NamedTemplate {
//使用具名引數模板
private ApplicationContext ioc=null;
private NamedParameterJdbcTemplate namedParameterJdbcTemplate=null;
{
ioc=new ClassPathXmlApplicationContext("bean-jdbc.xml");	
namedParameterJdbcTemplate=ioc.getBean(NamedParameterJdbcTemplate.class);
}

public void testparam(){
String sql="insert into user values(:num,:name,:kind)";
Map<String,String> map=new HashMap<String,String>();
map.put("num", "7");
map.put("name", "橋本環奈");
map.put("kind", "演員");
namedParameterJdbcTemplate.update(sql, map);	
}
public static void main(String[] args) {
	NamedTemplate na=new NamedTemplate();
	na.testparam();
}
}

結果如下

但是這樣的話,對於引數比較多的,新增多條資料的話,很不方便 ;


解決方案

//使用具名引數
public void paramTemplate(){
	String sql="insert into user"
             +" values(:number,:name,:kinds)";
	User u=new User("8", "蘇麻喇姑", "侍女");
	SqlParameterSource paramSource=new BeanPropertySqlParameterSource(u);
	namedParameterJdbcTemplate.update(sql, paramSource);
}

前提是,這個:number :name :kinds的名字和User類名裡面的屬性名稱要一致,不然會報錯

Exception in thread "main" org.springframework.dao.InvalidDataAccessApiUsageException: No value supplied for the SQL parameter 'kind': Invalid property 'kind' of bean class [cn.com.day03.User]: Bean property 'kind' is not readable or has an invalid getter method: Does the return type of the getter match the parameter type of the setter?