4、JDBC
(1)JDBC概要
l 使JDBC使用更容易,更少出错
l 由框架来处理资源的创建和释放
l 由框架来管理异常处理
(2)JdbcTemplate
l 执行SQL查询、更新语句和存储过程调用
l 循环遍历ResultSet和提取返回的参数值
l 例子:
DataSource ds = DataSourceUtils.getDataSourceFromJndi("MyDS");
JdbcTemplate jdbc = new JdbcTemplate(ds);
jdbc.execute("drop table TEMP");
jdbc.update("update EMPLOYEE set FIRSTNME=? where LASTNAME=?",
new String[] {"JOE", "LEE"});
l 使用方便方法进行查询
int maxAge = jdbc.queryForInt("select max(AGE) from EMPLOYEE");
String name = (String)jdbc.queryForObject(
"select FIRSTNME from EMPLOYEE where LASTNAME='LEE'", String.class);
List employees = jdbc.queryForList(
"select EMPNO, FIRSTNME, LASTNAME from EMPLOYEE");
返回一个ArrayList(一个条目对应一行)的HashMap(一个条目对应一列,使用列名做key)
l 使用回调方法查询
final List employees = new LinkedList();
jdbc.query("select EMPNO, FIRSTNME, LASTNAME from EMPLOYEE",
new RowCallbackHandler() {
public void processRow(ResultSet rs) throws SQLException {
Employee e = new Employee();
e.setEmpNo(rs.getString(1));
e.setFirstName(rs.getString(2));
e.setLastName(rs.getString(3));
employees.add(e);
}
});
l 存储过程
jdbc.call(new CallableStatementCreator() {
public CallableStatement createCallableStatement(Connection conn)
throws SQLException {
return conn.prepareCall("my query");
}
}, params);
l 批更新
BatchPreparedStatementSetter setter =
new BatchPreparedStatementSetter() {
public void setValues(PreparedStatement ps, int i)
throws SQLException {
...
}
public int getBatchSize() {
return ...;
}
};
jdbc.batchUpdate("update ...", setter);
(3)SqlQuery/SqlUpdate对象
l 封装查询和更新到Java类中
class EmployeeQuery extends MappingSqlQuery {
public EmployeeQuery(DataSource ds) {
super(ds, "select EMPNO, FIRSTNME, LASTNAME from EMPLOYEE where EMPNO = ?");
declareParameter(new SqlParameter(Types.CHAR));
compile();
}
protected Object mapRow(ResultSet rs, int rownum) throws SQLException {
Employee e = new Employee();
e.setEmpNo(rs.getString("EMPNO"));
e.setFirstName(rs.getString("FIRSTNME"));
e.setLastName(rs.getString("LASTNAME"));
return e;
}
public Employee findEmployee(String id) {
return (Employee) findObject(id);
}
}
映射结果集的行到一个Java对象
(4)SqlFunction
l 封装返回单行的查询
SqlFunction sf = new SqlFunction(dataSource,
"select count(*) from mytable");
sf.compile();
int rows = sf.run();
(5)异常处理
l 转换SQLExecption到DataAccessException层面
Ø 通用,更多信息,与DB/JDBC无关(sql错误代码被映射到异常)
l 使用RuntimeException(没有检查)
l 我们可以覆盖未检查的数据访问异常
try {
// do work
} catch (OptimisticLockingFailureException ex) {
// I'm interested in this
}
(6)数据库连接
l DataSourceUtils:getConnection()、getDatSourceFromJndi()、closeConnectionIfNecessary()
l DriverManagerDataSource
Ø 每次返回一个新的连接
Ø 能够在容器外或测试中使用
l SingleConnectionDataSource
Ø 每次返回同一个连接
Ø 能够在容器外或测试中使用