A Generic JDBC Abstraction Framework(5)--Using the JdbcTemplate Class

Using the JdbcTemplate Class

用jdbctemplate类

Now that we've looked at the implementation, let's see the com.interface21.jdbc.core package in action.

闲杂我们已经探讨了实现,让我们在应用中理解com.interface21.jdbc.core包。

Performing Queries

执行查询

Using the JdbcTemplate class, we can accomplish the JDBC query for seat IDs, shown under Motivation above, as follows, using anonymous inner classes to implement the RowCallbackHandler and PreparedStatementCreator interfaces. This implementation of RowCallbackHandler saves data in a list of Integers defined in the enclosing method:

用jdbcTemplate类,我们能完成座位id的jdbc查询,在下面,用匿名内部类去实现RowCallbackHandlerPreparedStatementCreator 接口。

RowCallbackHandler的实现把数据保存在一个整形的列表中。

public List getAvailableSeatIdsWithJdbcTemplate(
DataSource ds, final int performanceId, final int seatType)
throws DataAccessException {
JdbcTemplate t = new JdbcTemplate(ds);
final List 1 = new LinkedList();
PreparedStatementCreator psc = new PreparedStatementCreator() {
public PreparedStatement createPreparedStatement(Connection conn)
throws SQLException {
PreparedStatement ps = conn.prepareStatement(
"SELECT seat_id AS id FROM available_seats WHERE " +
"performance_id = ? AND price_band_id = ?");
ps.setInt(1, performanceId);
ps.setInt(2, seatType);
return ps;
}
};
RowCallbackHandler rch = new RowCallbackHandler() {
public void processRow(ResultSet rs) throws SQLException {
int seatId = rs.getInt(1);
1.add(new Integer(seatId));
}
};
t.query(psc, rch);
return 1;
}

This halves the amount of code required and addresses most of the problems we identified in using the JDBC API directly. We can work with PreparedStatement and ResultSet objects with a minimum of irrelevant code. Most importantly, using the JdbcTemplate class eliminates the major causes of errors. There is no risk that the connection won't be closed: the JdbcTemplate class ensures this. Application code doesn't need to catch checked, uninformative SQLExceptions: our generic data access exception hierarchy offers a richer classification of exceptions, but, since data access exceptions are unchecked, application code can typically leave exceptions to be dealt with by the application server.

这部分所需代码的数量和解决了我们用直接jdbc api出现的大部分问题。我们能与PreparedStatementResultSet 一起工作用一个最小不相干的代码。更重要的是,用JdbcTemplate 类消除了错误的主要起因。连接将不被关闭的风险是没有的:JdbcTemplate 类确保了这个。应用代码不需要捕获检查异常,不提供SQLExceptions信息:我们的通用数据访问异常层次提供了一个更丰富的异常级别,但是,因为数据访问异常未经检查的,应用代码能通常留下异常被应用服务处理。

Performing Updates

执行更新

If we use the JDBC API directly, updates call for a similar amount of code to queries. Again error handling is dominant and the SQL we want to execute is obscured. Again the JdbcTemplate class can deliver real benefits. The JdbcTemplate update() method is capable of running updates using the PreparedStatementCreator callback interface we've already seen. The following example (not part of our sample application!) would delete all seat reservations and bookings for a particular seat type in a given performance. The example assumes we already have a JdbcTemplate object in scope. As JdbcTemplate objects are threadsafe, we will normally keep one as an instance variable in DAO implementations usingJDBC:

如果我们直接用jdbc api,更新与查询的代码类似。再次错误处理是显然的,我们想要执行的sql被掩盖了。再次用JdbcTemplate类可以带来真正的好处。

jdbcTemplate的 update()方法有能力用PreparedStatementCreator 回调接口运行更新。

class PerformanceCleanerPSC implements PreparedStatementCreator {
private int pid;
private int pb;
public PerformanceCleanerPSC(int pid, int pb) {
this.pid = pid;
this.pb = pb;
}
public PreparedStatement createPreparedStatement(Connection conn)
throws SQLException {
PreparedStatement ps = conn.prepareStatement("UPDATE seat_status " +
"SET booking_id = null WHERE performance_id = ? AND " +
"price_band_id = ?");
ps.setInt(1, pid);
ps.setInt(2, pb);
return ps;
}
};
PreparedStatementCreator psc = new PerformanceCleanerPSC (1, 1);
int rowsAffected = jdbcTemplate.update(psc);

Updates using static SQL are even easier. The following example would mark all seats in our ticketing application as available, without any need to implement callback interfaces:

template.update("UPDATE SEAT_STATUS SET BOOKING_ID = NULL");

转载于:https://www.cnblogs.com/sqtds/archive/2012/12/09/2810475.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值