Using "functional"-Programming to map Resultsets to POJOs
When I use jdbc to develop a small tool, where using a OR-Mapper like Hibernate is overkill, I always dislike that i have to dublicate all the "getStatement" "execQuery" "while (resultSet.next())" stuff.
i dont like to repeat stuff in my code. It would be very easy if java had closures, but i dont want to wait until java7 to simplify my code so I needet another idea.
java has no closures but it has something that can be used in a similar manner - Anonymous inner classes.
so to simplify the following class
Connection con = getConnection()
Statement st = con.createStatement();
ResultSet rs = st.executeQuery( "sqlstring");
List<Foo> result = new ArrayList<Foo>();
while (rs.next()) {
Foo f = new Foo();
f.setProperty1( rs.getString( "property1" ));
f.setProperty2( rs.getString( "property2" ));
result.add( f );
}
// imagine catch/finaly block here
st.close();
con.close();
i define a interface called Function
interface Function<T> {
public T valueOf( ResultSet rs ) throws SQLException;
}
Then i define a QueryMapper like this
public class QueryMapper<T> {
private Database db;
public QueryMapper( Database db ) {
this.db = db;
}
List<T> listOf( Function<T> f, String query ) {
List<T> res = new ArrayList<T>();
Resultset rs = ... get resultset for query ..
while ( rs.next() ) {
res.add( f.valueOf( rs ));
}
// catch/finaly block here
return res;
}
}
So all i have to do in my code now is calling
Function<Foo> fn = new Function<Foo>() {
public Foo valueOf( ResultSet rs) throws SQLException {
Foo res = new Foo();
res.setPropery1( rs.getString( "property1" ));
res.setPropery2( rs.getString( "property2" ));
return res;
}
}
QueryMapper<Foo> qm = QueryMapper<Foo>( db );
List<Foo> res = qm.listOf( fn, "select * from foo");
I can even recycle the Function objects ( if i query different object of the same type but with different ids for example ) thats more how i like it
See also:
File Upload in Servlet 3.0
OutOfIdeasException
Deploying Processing apps using WebStart
Handassembled java bytecode
Simple but useful...
I agree with that Taner. :)