我写了提到自定义出站通道适配器,它使用spring-jdbc批处理能力:
public class ArrayListSqlBatchOBCA {
private final static Logger log = LoggerFactory.getLogger(ArrayListSqlBatchOBCA.class);
private NamedParameterJdbcTemplate template;
private String sql;
public void process(Message<? extends ArrayList<?>> message) throws Exception {
try {
ArrayList<?> list = (ArrayList<?>) message.getPayload();
SqlParameterSource[] batchArgs = new SqlParameterSource[list.size()];
for (int i = 0; i < list.size(); i++) {
batchArgs[i] = new BeanPropertySqlParameterSource(list.get(i));
}
template.batchUpdate(sql, batchArgs);
}
catch (Exception e) {
log.error("Exception while processing message", e);
throw e;
}
}
}
这就是我使用它的方式(XML 配置):
<channel id="cc"/>
<outbound-channel-adapter channel="cc" method="process">
<beans:bean class="mypackage.ArrayListSqlBatchOBCA">
<beans:property name="template" ref="jdbcTemplate"/>
<beans:property name="sql"
value="INSERT INTO test (field1,field2,field3)
VALUES (:f1,:f2,:f3)"/>
</beans:bean>
</outbound-channel-adapter>
此外,我在数据源的 jdbc url 中添加了 ?reWriteBatchedInserts=true(我使用 postgres JDBC 驱动程序)。
Documentation about the option:
reWriteBatchedInserts - 启用优化以重写和折叠批处理的兼容 INSERT 语句。如果启用,pgjdbc 将一批insert into ... values(?, ?) 重写为insert into ... values(?, ?), (?, ?), ...
这样,使用一个小的自定义代码,我从输入集合中一次插入多行。