Reputation: 217
I am in the process of converting creation of connection to use JdbcTemplate class which handles the creation and release of resources. One of the implementation shown below is not returning me a resultset though the original one for the same query returns me records. I converted the below code
ps = connection.prepareStatement(strQuery, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
ps.setLong(1, getId());
objRs = ps.executeQuery();
to the one shown below. The reason I used a StreamingStatementCreator was because I needed to set ResultSet.TYPE_SCROLL_INSENSITIVE and ResultSet.CONCUR_READ_ONLY.
objRs = (ResultSet) jdbcTemplate.query(new StreamingStatementCreator(strQuery),
new PreparedStatementSetter() {
public void setValues(PreparedStatement preparedStatement) throws SQLException {
preparedStatement.setLong(1, getId());
}
}, new CustomResultSetExtractor());
public class CustomResultSetExtractor implements ResultSetExtractor<ResultSet>{
public ResultSet extractData(ResultSet resultSet) throws SQLException, DataAccessException {
return resultSet;
}
}
I am not familiar with these methods. I tried to look for examples and I feel the code is correct by maybe I missing something. The first case returns me value in objRs and the second returns me nothing.
Upvotes: 0
Views: 1586
Reputation: 217
Based on the clue by Alexander, made use of the ColumnMapRowMapper to iterate the result set. Since I wanted a generic solution that I could use for all my queries, instead of processing the resultset in my CustomResultSetExtractor or create separate classes. I am adding the code here so that anyone else who comes across this same situation may find it useful.
public class CustomResultSetExtractor implements ResultSetExtractor<Object>{
private RowMapper<Map<String, Object>> mapper;
public CustomResultSetExtractor(ColumnMapRowMapper mapper) {
this.mapper = mapper;
}
public List<Map<String, Object>> extractData(ResultSet rs) throws SQLException, DataAccessException {
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
int row = 0;
while(rs.next()){
Map<String, Object> o = (Map<String, Object>)mapper.mapRow(rs, row++);
list.add(o);
}
return list;
}
}
Upvotes: 0
Reputation: 870
Method query(PreparedStatementCreator psc, ResultSetExtractor<T> rse)
Does not returns ResultSet
. It calls second parameter with ResultSet
as argument and returns object that was returned by it.
So you shoud process ResultSet
in CustomResultSetExtractor
and return onther object as a result of processing.
Upvotes: 1