爲啥spring 要開發這個 NamedParameterJdbcTemplate 他解決了在可變參數中的匹配不正確 在參數列表中 ? 對應的索引號 如果出現了新增參數改變起來很不方便而且還容易處錯誤這就是它的由來
下面看看它如何使用的 並體會下
import org.junit.Before;
import org.junit.Test;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
public class SJTest2 {
NamedParameterJdbcTemplate nam = null;
@Before
public void init() {
DriverManagerDataSource ds = new DriverManagerDataSource();
ds.setDriverClassName("com.mysql.jdbc.Driver");
ds.setUrl("jdbc:mysql://127.0.0.1:3306/test");
ds.setUsername("root");
ds.setPassword(""); // 我的數據庫沒有密碼
nam = new NamedParameterJdbcTemplate(ds);
}
/**
* 這種 " : " 用法在 hibernate 裏面也有提供。
*/
@Test
public void insert() {
Student stu = new Student();
stu.setSid(19);
stu.setAge("100");
String sql = "insert into student(sid,age) values(:sid,:age)";
SqlParameterSource sps = new BeanPropertySqlParameterSource(stu);
nam.update(sql, sps);
}
@Test
public void insert2() {
Student stu = new Student();
stu.setAge("200");
stu.setSid(20);
// . . 這種是一種簡單的鏈式編程內部返回自身
String sql = "insert into student(sid,age) values(:sid,:age)";
MapSqlParameterSource sps = new MapSqlParameterSource().addValue("sid", stu.getSid())
.addValue("age", stu.getAge());
nam.update(sql, sps);
}
class Student {
private long sid;
private String age;
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public long getSid() {
return sid;
}
public void setSid(long sid) {
this.sid = sid;
}
@Override
public String toString() {
return "Student [sid=" + sid + ", age=" + age + "]";
}
}
}