Usually I apply it only when I have to made a change, and realize, I have to do it at too many places. I don't like it because it is a bit confusing, especially the stack traces.
Here is an example taken from a db connection.
public abstract class Template{
String sql ;
Template(String sql){
this.sql = sql;
}
public void exec() {
Statement statement = null;
ResultSet rs = null;
try {
statement = getConnection().createStatement();
rs = statement.executeQuery(sql);
execute(rs);
} catch (SQLException e) {
log.error("failed to execute query " + sql);
throw e;
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
log.error("failed to close result set");
}
}
if (statement != null) {
statement.close();
}
}
public abstract void execute(ResultSet resultSet);
}
The problem lies in retrieving something from the execute method
final Listresults = new ArrayList ();
Template call = new Template(sql) {
@Override
public void execute(ResultSet rs) throws SQLException {
rs.next();
Boolean result = rs.getBoolean("BoolColumn");
results.add(result);
}
};
call.exec();
boolean result = results.get(0);
Maybe I missed something, but It is the best way I found for retrieving a value.
No comments:
Post a Comment