spring對jdbc的支持

早就知道spring對jdbc有很好的支持,這幾天看書和代碼才知道, spring就是用了幾個模式把那些煩人的try catch,資源管理,還有事務控制等一堆重複且不美觀的東西隱藏起來, 以spring ioc 不侵入代碼的特性,給我們省了不少事兒,讓我們的代碼更美觀簡潔。反過來說,我們重構下自己的代碼,也能搞出個“spring jdbc”來, 呵呵。大言不慚了。主要還是說, 學學spring對模式的運用, 用到我們自己的項目中來,也得瑟下,呵呵。
重點就是,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;
}


}
發佈了31 篇原創文章 · 獲贊 4 · 訪問量 1662
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章