Spring JDBC 對原生 JDBC 做了一層封裝,把資源關閉、例外轉換這些瑣事收攏起來,只留下 SQL 本身。它的核心類是 JdbcTemplate,為各類資料庫操作提供了現成的模板方法。就定位而言,JdbcTemplate 之於 Spring JDBC,等同於 DbUtils 之於原生 JDBC,兩者做的是同一件事。
在 Spring 配置檔中先聲明資料源,再把資料源交給 JdbcTemplate:
<context:property-placeholder location="classpath:db.properties"/>
<bean class="com.mchange.v2.c3p0.ComboPooledDataSource" id="dataSource">
<property name="driverClass" value="${jdbc.driverClass}"/>
<property name="jdbcUrl" value="${jdbc.jdbcUrl}"/>
<property name="user" value="${jdbc.user}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"/>
</bean>
之後在目標類中直接注入使用:
@Repository
public class StudentDao {
@Autowired
private JdbcTemplate jdbcTemplate;
}
新增一筆資料,方法回傳受影響的行數:
public void insertStudent() {
String sql = "insert into student(student_id, student_name, student_class) values(?,?,?)";
int affectRows = this.jdbcTemplate.update(sql, 1, "tom", "0102");
System.out.println("affectRows:" + affectRows);
}
若需要拿回資料庫產生的主鍵,則要借助 PreparedStatementCreator 與 KeyHolder:
public void insertStudent2() {
PreparedStatementCreator psc = new PreparedStatementCreator() {
@Override
public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
String sql = "insert into student(student_id, student_name, student_class) values(?, ?, ?)";
PreparedStatement ps = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
ps.setInt(1, 2);
ps.setString(2, "jerry");
ps.setString(3, "0805");
return ps;
}
};
KeyHolder keyHolder = new GeneratedKeyHolder();
this.jdbcTemplate.update(psc, keyHolder);
System.out.println(keyHolder.getKey());
}
批量新增則把多組參數收進 List,一次交給 batchUpdate:
public void batchUpdate() {
String sql = "insert into student(student_id, student_name, student_class) values(?, ?, ?)";
List<Object[]> list = new ArrayList<>();
list.add(new Object[]{3, "lily", "0806"});
list.add(new Object[]{4, "lucy", "0807"});
this.jdbcTemplate.batchUpdate(sql, list);
}
查單一物件時,用 BeanPropertyRowMapper 直接把結果集對映成 JavaBean:
public void getStudent(Integer id) {
String sql = "select student_id, student_name, student_class from student where student_id = ?";
RowMapper<Student> rowMapper = new BeanPropertyRowMapper<>(Student.class);
Student student = this.jdbcTemplate.queryForObject(sql, rowMapper, id);
System.out.println(student);
}
輸出:Student{studentId=1, studentName='tom', studentClass='0804'}
只取一個統計值時,直接指定目標型別即可:
public void getCount() {
String sql = "select count(student_id) from student";
Long count = this.jdbcTemplate.queryForObject(sql, Long.class);
System.out.println(count);
}
同樣需要在配置檔中註冊實例。使用時可以用 Map 傳值:
public void insert() {
String sql = "insert into student(student_id, student_name, student_class) values(:studentId, :studentName, :studentClass)";
Map<String, Object> paramMap = new HashMap<>();
paramMap.put("studentId", 5);
paramMap.put("studentName", "jakc");
paramMap.put("studentClass", "0808");
this.namedParameterJdbcTemplate.update(sql, paramMap);
}
也可以直接讓它從 JavaBean 取屬性,省去組 Map 的麻煩:
public void insert2() {
String sql = "insert into student(student_id, student_name, student_class) values(:studentId, :studentName, :studentClass)";
Student student = new Student();
student.setStudentId(6);
student.setStudentName("mary");
student.setStudentClass("0809");
SqlParameterSource source = new BeanPropertySqlParameterSource(student);
this.namedParameterJdbcTemplate.update(sql, source);
}
需要主鍵時,多傳一個 KeyHolder 就好:
public void insert3() {
String sql = "insert into student(student_id, student_name, student_class) values(:studentId, :studentName, :studentClass)";
Student student = new Student();
student.setStudentId(7);
student.setStudentName("kobe");
student.setStudentClass("0810");
SqlParameterSource source = new BeanPropertySqlParameterSource(student);
KeyHolder keyHolder = new GeneratedKeyHolder();
this.namedParameterJdbcTemplate.update(sql, source, keyHolder);
System.out.println(keyHolder.getKey());
}
讓 DAO 繼承 JdbcDaoSupport,就不必在配置檔裡聲明 JdbcTemplate,容器會自動注入;但每個目標類都要各自配置資料源,而且不能再用 @Autowired 去注入 dataSource。
@Repository
public class PersonDao extends JdbcDaoSupport {
public void insert() {
String sql = "insert into person(id, person_name) values(?, ?)";
this.getJdbcTemplate().update(sql, 1, "tom");
}
}
<bean class="com.nucsoft.spring.jdbc.PersonDao" id="dao">
<property name="dataSource" ref="dataSource"/>
</bean>