在本案的第二階段,找回過去的戰友加入本案。正好湊成一個完整的JDBCTemplate使用Bean對映方式的Solution。在想把Java Bean對映到SQL裡,中間需要Mapping,雖然Mapping方式可以Code Generator,但仍然是段食之無味的程式碼。而若用Bean Process方式在如下Sample:
1. Create Table foo (id number(10) primary key, name varchar2(10)); // 建立demo用的table。
2. 根據Table產生Java Bean(又稱Value Object或Persistence Object),吾採後者為FooPo,內容略…。
3. 寫FooDao繼承Spring的JdbcDaoSupport,該Dao的insert method如下:
public void insertFoo(FooPo po) throws Exception {
String sql = "insert into foo (id, name) values (:id, :name)";
SqlParameterSource namedParameters = new BeanPropertySqlParameterSource(po);
NamedParameterJdbcTemplate pstmt = new NamedParameterJdbcTemplate(this.getDataSource());
pstmt.update(sql, namedParameters);
}
如此,SQL的:id與:name透過BeanPropertySqlParameterSource設定對應到FooPo的getId()和getName()。修改、刪除亦如是。
那查詢也是否能如此對映呢?原本要自己動手做如下的Mapping:
getJdbcTemplate().query("select * from foo", new RowMapper() {
public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
FooPo po = new FooPo;
po.setId(rs.getInteger("ID"));
po.setName(rs.getString("NAME"));
return po;
}
};
而使用Apache的commons的dbutils的BeanProcessor則可以省略上述的工:
import org.apache.commons.dbutils.BeanProcessor;
public List<FooPo> queryById(Integer id) throws Exception {
String sql = "select * from foo where id=?";
return (List) getJdbcTemplate().query(sql, new Object[]{id}, new ResultSetExtractor() {
public Object extractData(ResultSet rs) throws SQLException, DataAccessException {
BeanProcessor beanProcessor = new BeanProcessor();
return beanProcessor.toBeanList(rs, FooPo.class);
}
});
}