01: package liquibase.database.template;
02:
03: import java.sql.ResultSet;
04: import java.sql.SQLException;
05: import java.util.ArrayList;
06: import java.util.List;
07:
08: /**
09: * Adapter implementation of the ResultSetExtractor interface that delegates
10: * to a RowMapper which is supposed to create an object for each row.
11: * Each object is added to the results List of this ResultSetExtractor.
12: * <p/>
13: * <p>Useful for the typical case of one object per row in the database table.
14: * The number of entries in the results list will match the number of rows.
15: * <p/>
16: * <p>Note that a RowMapper object is typically stateless and thus reusable;
17: * just the RowMapperResultSetExtractor adapter is stateful.
18: * <p/>
19: * <p>A usage example with JdbcTemplate:
20: * <p/>
21: * <pre class="code">JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); // reusable object
22: * RowMapper rowMapper = new UserRowMapper(); // reusable object
23: * <p/>
24: * List allUsers = (List) jdbcTemplate.query(
25: * "select * from user",
26: * new RowMapperResultSetExtractor(rowMapper, 10));
27: * <p/>
28: * User user = (User) jdbcTemplate.queryForObject(
29: * "select * from user where id=?", new Object[] {id},
30: * new RowMapperResultSetExtractor(rowMapper, 1));</pre>
31: * <p/>
32: *
33: * @author Spring Framework
34: * @see RowMapper
35: * @see JdbcTemplate
36: */
37: @SuppressWarnings({"unchecked"})
38: class RowMapperResultSetExtractor implements ResultSetExtractor {
39:
40: private final RowMapper rowMapper;
41:
42: private final int rowsExpected;
43:
44: /**
45: * Create a new RowMapperResultSetExtractor.
46: *
47: * @param rowMapper the RowMapper which creates an object for each row
48: */
49: public RowMapperResultSetExtractor(RowMapper rowMapper) {
50: this (rowMapper, 0);
51: }
52:
53: /**
54: * Create a new RowMapperResultSetExtractor.
55: *
56: * @param rowMapper the RowMapper which creates an object for each row
57: * @param rowsExpected the number of expected rows
58: * (just used for optimized collection handling)
59: */
60: public RowMapperResultSetExtractor(RowMapper rowMapper,
61: int rowsExpected) {
62: this .rowMapper = rowMapper;
63: this .rowsExpected = rowsExpected;
64: }
65:
66: public Object extractData(ResultSet rs) throws SQLException {
67: List results = (this .rowsExpected > 0 ? new ArrayList(
68: this .rowsExpected) : new ArrayList());
69: int rowNum = 0;
70: while (rs.next()) {
71: results.add(this.rowMapper.mapRow(rs, rowNum++));
72: }
73: return results;
74: }
75:
76: }
|