如果您有需要映射到的对象...
考虑使用自定义实现为 SQL 指定别名以匹配对象字段名称RowMapper
这实际上延伸了BeanWrapperFieldSetMapper
所以如果你的 POJO 看起来像这样:
public class Employee {
private String employeeId;
private String employeeName;
...
// getters and setters
}
那么你的 SQL 可以是这样的:
SELECT emp_id employeeId, emp_name employeeName from employee_table
然后你的包裹RowMapper
看起来像这样:
import org.springframework.jdbc.core.RowMapper
import org.springframework.batch.item.file.mapping.BeanWrapperFieldSetMapper
public class BeanWrapperRowMapper<T> extends BeanWrapperFieldSetMapper<T> implements RowMapper<T> {
@Override
public T mapRow(final ResultSet rs, final int rowNum) throws SQLException {
final FieldSet fs = getFieldSet(rs);
try {
return super.mapFieldSet(fs);
} catch (final BindException e) {
throw new IllegalArgumentException("Could not bind bean to FieldSet", e);
}
}
private FieldSet getFieldSet(final ResultSet rs) throws SQLException {
final ResultSetMetaData metaData = rs.getMetaData();
final int columnCount = metaData.getColumnCount();
final List<String> tokens = new ArrayList<>();
final List<String> names = new ArrayList<>();
for (int i = 1; i <= columnCount; i++) {
tokens.add(rs.getString(i));
names.add(metaData.getColumnName(i));
}
return new DefaultFieldSet(tokens.toArray(new String[0]), names.toArray(new String[0]));
}
}
或者...
如果您没有任何要映射到的 POJO,请使用现成的ColumnMapRowMapper
拿回地图(Map<String,Object>
)的列名(我们称它们为 COL_A、COL_B、COL_C)到值。那么如果你的作家是这样的JdbcBatchItemWriter
您可以将命名参数设置为:
INSERT TO ${schema}.TARGET_TABLE (COL_1, COL_2, COL_3) values (:COL_A, :COL_B, :COL_C)
然后你的ItemSqlParameterSourceProvider
实现可能如下所示:
public class MapItemSqlParameterSourceProvider implements
ItemSqlParameterSourceProvider<Map<String, Object>> {
public SqlParameterSource createSqlParameterSource(Map<String, Object> item) {
return new MapSqlParameterSource(item);
}
}