整个数据库访问层的实现模式是:domain类(User)+Dao接口(UserDao)+Dao接口实现(UserDaoImpl)
数据库的操作就是“更、删、改、查”,有称CRUD:
1.“更、删、改”可以统一为对数据库的update操作,所以可以定义一个模板方法:
protected int update(String sql, Object[] args) {
Connection conn = null;
PreparedStatement ps = null;
try {
// 建立连接
conn = JdbcUtils.getConnection();
// 创建语句
ps = conn.prepareStatement(sql);
// 设置参数
setParameters(args, ps);
// 执行语句
int returnint = ps.executeUpdate();
return returnint;
} catch (SQLException e) {
throw new DaoException(e.getMessage(), e);
} finally {
JdbcUtils.getInstance().free(null, ps, conn);
}
}
2.”查询“麻烦一点,因为不同的表的查询,ResultSet中的数据不一样,必须做不同的处理,定义下面这个模板方法,可以比较好的处理这个问题:
protected Object find(String sql, Object[] args, RowMapper rowMapper) {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
Object obj = null;
try {
// 建立连接
conn = JdbcUtils.getConnection();
// 创建语句
ps = conn.prepareStatement(sql);
// 设置参数
setParameters(args, ps);
// 执行语句
rs = ps.executeQuery();
// 处理结果
while (rs.next()) {
obj = rowMapper.mapRow(rs);
}
} catch (SQLException e) {
throw new DaoException(e.getMessage(), e);
} finally {
JdbcUtils.getInstance().free(rs, ps, conn);
}
return obj;
}
具体代码见:dao.impl.AbstactDaoImpl2
说明:定义了一个RowMapper的接口,把ResultSet的处理交给它的调用者,这种思想很好。
public interface RowMapper {
public Object mapRow(ResultSet rs) throws SQLException;
}
具体代码见:dao.impl.RowMapper
3.具体的Dao接口实现见dao.impl.UserDaoImpl2类。