Java Reference
In-Depth Information
2.2 How it works
More than anything else, i BATIS is an alternative to writing JDBC and ADO.NET
code. API s like JDBC and ADO.NET are powerful, but tend to be verbose and repet-
itive. Consider the JDBC example in listing 2.2.
Listing 2.2
Example of well-written JDBC code
public Employee getEmployee (int id) throws SQLException {
Employee employee = null;
String sql = "SELECT * FROM EMPLOYEE " +
"WHERE EMPLOYEE_NUMBER = ?";
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = dataSource.getConnection();
ps = conn.prepareStatement(sql);
ps.setInt(1, id);
rs = ps.executeQuery();
employee = null;
while (rs.next()) {
employee = new Employee();
employee.setId(rs.getInt("ID"));
employee.setEmployeeNumber(rs.getInt("EMPLOYEE_NUMBER"));
employee.setFirstName(rs.getString("FIRST_NAME"));
employee.setLastName(rs.getString("LAST_NAME"));
employee.setTitle(rs.getString("TITLE"));
}
} finally {
try {
if (rs != null) rs.close();
} finally {
try {
if (ps != null) ps.close();
} finally {
if (conn != null) conn.close();
}
}
}
return employee;
}
Our SQL is buried here
It's easy to see the overhead created by the JDBC API . Every line is necessary,
though, so there's no easy way to reduce it. At best, a few of the lines can be
extracted into utility methods, most notably the closing of resources such as the
PreparedStatement and the ResultSet .
Search WWH ::




Custom Search