01: package liquibase.database.template;
02:
03: import liquibase.util.JdbcUtils;
04:
05: import java.sql.ResultSet;
06: import java.sql.ResultSetMetaData;
07: import java.sql.SQLException;
08: import java.util.LinkedHashMap;
09: import java.util.Map;
10:
11: /**
12: * {@link RowMapper} implementation that creates a <code>java.util.Map</code>
13: * for each row, representing all columns as key-value pairs: one
14: * entry for each column, with the column name as key.
15: * <p/>
16: * <p>The Map implementation to use and the key to use for each column
17: * in the column Map can be customized through overriding
18: * {@link #createColumnMap} and {@link #getColumnKey}, respectively.
19: * <p/>
20: *
21: * @author Spring Framework
22: */
23: @SuppressWarnings({"unchecked"})
24: class ColumnMapRowMapper implements RowMapper {
25:
26: public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
27: ResultSetMetaData rsmd = rs.getMetaData();
28: int columnCount = rsmd.getColumnCount();
29: Map mapOfColValues = createColumnMap(columnCount);
30: for (int i = 1; i <= columnCount; i++) {
31: String key = getColumnKey(rsmd.getColumnName(i));
32: Object obj = getColumnValue(rs, i);
33: mapOfColValues.put(key, obj);
34: }
35: return mapOfColValues;
36: }
37:
38: /**
39: * Create a Map instance to be used as column map.
40: * @param columnCount the column count, to be used as initial
41: * capacity for the Map
42: * @return the new Map instance
43: */
44: protected Map createColumnMap(int columnCount) {
45: return new LinkedHashMap(columnCount);
46: }
47:
48: /**
49: * Determine the key to use for the given column in the column Map.
50: *
51: * @param columnName the column name as returned by the ResultSet
52: * @return the column key to use
53: * @see java.sql.ResultSetMetaData#getColumnName
54: */
55: protected String getColumnKey(String columnName) {
56: return columnName;
57: }
58:
59: /**
60: * Retrieve a JDBC object value for the specified column.
61: * <p>The default implementation uses the <code>getObject</code> method.
62: * Additionally, this implementation includes a "hack" to get around Oracle
63: * returning a non standard object for their TIMESTAMP datatype.
64: *
65: * @param rs is the ResultSet holding the data
66: * @param index is the column index
67: * @return the Object returned
68: */
69: protected Object getColumnValue(ResultSet rs, int index)
70: throws SQLException {
71: return JdbcUtils.getResultSetValue(rs, index);
72: }
73:
74: }
|