数据库访问层的实现(一)——模板方法模式

整个数据库访问层的实现模式是: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类。

 

 

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值