早就知道spring对jdbc有很好的支持,这几天看书和代码才知道, spring就是用了几个模式把那些烦人的try catch,资源管理,还有事务控制等一堆重复且不美观的东西隐藏起来, 以spring ioc 不侵入代码的特性,给我们省了不少事儿,让我们的代码更美观简洁。反过来说,我们重构下自己的代码,也能搞出个“spring jdbc”来, 呵呵。大言不惭了。主要还是说, 学学spring对模式的运用, 用到我们自己的项目中来,也得瑟下,呵呵。
重点就是,spring jdbc框架用了模板方法模式和回调。数据访问的步骤是固定的且必须的。
我们总是要和数据库建立连接, 在操作完后释放资源。这就是数据访问流程中的固定步骤。但是数据访问的实现都略有不同,会用不同的方式查询不通的对象、更新数据,这些是数据访问流程中可变的步骤。spring把数据访问流程中固定部分和可变部分分开,分别映射成两个截然不同的类:模板和回调。
举个例子来看,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;
}
}