Spring JDBC Framework simplifies the use of JDBC and helps to avoid common errors.
The following example shows using ResultSetExtractor interface.
This callback interface is useful for processing the entire resultset. The RowLimitResultSetExtractor
given in this examples limits the number of records to process by user given value.
/**
* Initialize context and get the JdbcTemplate
*/
ApplicationContext appContext = new ClassPathXmlApplicationContext("applicationContext.xml");
DataSource dataSource = (DataSource) appContext.getBean("dataSource");
JdbcTemplate template = new JdbcTemplate(dataSource);
int limitRowsBy = 2;
List<User> users = template.query(
"select ID as userId, NAME as userName, age, salary from USER", new RowLimitResultSetExtractor<User>( new BeanPropertyRowMapper<User>(User.class), limitRowsBy));
System.out.println(users);
List<BugStat> stats = template.query(
"select ID as bugStatId, STATUS as bugStatus, COUNT as bugCount from BUG_STAT", new RowLimitResultSetExtractor<BugStat>( new BeanPropertyRowMapper<BugStat>(BugStat.class), limitRowsBy));
System.out.println(stats);
}
}
class RowLimitResultSetExtractor<T> implements ResultSetExtractor<List<T>> {
private RowMapper<T> rowMapper; private int limitBy;
public RowLimitResultSetExtractor(RowMapper<T> rowMapper, int limitBy) { this.rowMapper = rowMapper; this.limitBy = limitBy;
}
//Invoked only once for processing the entire result set.
@Override public List<T> extractData(ResultSet rs) throws SQLException, DataAccessException {
List<T> results = new ArrayList<T>(); int rowNum = 0; while (rs.next() && rowNum < limitBy) {
results.add(this.rowMapper.mapRow(rs, rowNum++));
} return results;
}
}