重點就是,spring jdbc框架用了模板方法模式和回調。數據訪問的步驟是固定的且必須的。
我們總是要和數據庫建立連接, 在操作完後釋放資源。這就是數據訪問流程中的固定步驟。但是數據訪問的實現都略有不同,會用不同的方式查詢不通的對象、更新數據,這些是數據訪問流程中可變的步驟。spring把數據訪問流程中固定部分和可變部分分開,分別映射成兩個截然不同的類:模板和回調。
[img]/upload/attachment/78755/37f397df-c65c-3ce7-9394-367e28afe4bc.bmp[/img]
舉個例子來看,spring 的jdbc template如何幫使我們的代碼簡化。
接口
public interface CustomerTypeDao
{
void save(CustomerType customerType);
CustomerType getById(Integer id);
}
實現
public class CustomerTypeImplDao implements CustomerTypeDao {
private JdbcTemplate jdbcTemplate;
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public void save(CustomerType customerType) {
String sql = "insert into customer_type(id, name) values(?,?)";
Object[] args = new Object[]{customerType.getId(),customerType.getName()};
int[] argTypes = new int[]{Types.INTEGER, Types.VARCHAR};
jdbcTemplate.update(sql, args, argTypes);
}
public CustomerType getById(Integer id) {
String sql = "select id, name from customer_type where id=?";
Object[] args = new Object[]{id};
final CustomerType customerType = new CustomerType();
jdbcTemplate.query(sql, args, new RowCallbackHandler(){
public void processRow(ResultSet rs) throws SQLException {
customerType.setId(rs.getInt("id"));
customerType.setName(rs.getString("name"));
}
});
return customerType;
}
}