Menu

#4 Map a ResultSet to a List

open
nobody
5
2005-09-05
2005-09-05
Federico
No

Many times using the api I end up loading objects from
a result set into a list and returning it. I wrote this
quick enhancement. It can be done without generics,
too. If you like the idea, you can add this
functionality in safejdbc.
I tried implementing this functionality directly inside
the API extending SQLExecuter and SQL, etc, but I feel
it was too much work just for a simple useful method.
It is possible to support transactions, too. Just
making minor changes.
Also, having generics in the ObjectHolder would be
nice, maybe forking the package, for java 1.5 and the rest.

public interface ResultSetTransformer<T> {
T transform(ResultSet rs) throws SQLException;
}
/*------------------*/
public interface MapSQL<T> {
public List<T> mapQuery(String prepSql,
FillingCommand fc,
final ResultSetTransformer<T> transformer)
throws SQLException;
}
/*------------------*/
public class SQLTransformer<T> implements SQL, MapSQL<T> {

private SQL sql;

public SQLTransformer(SQL sql) {
this.sql = sql;
}

public List<T> mapQuery(String prepSql,
FillingCommand fc,
final ResultSetTransformer<T> transformer)
throws SQLException {
final List<T> answer = new ArrayList<T>();
sql.query(prepSql, fc, new ResultSetIterator() {
public void forEachRow(ResultSet rs) throws
SQLException {
answer.add(transformer.transform(rs));
}
});
return answer;
}
... [here forward all the other SQL methods to this.sql]

Discussion


Log in to post a comment.

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.