好吧,讓它工作。我有我的方式入侵到Groovy的SQL類,有一些事情,我不能這樣做,因爲在Groovy類的方法是私有的,所以這個實現不支持cachedStatements,該isWithinBatch方法將無法工作正確地在閉包中,並且無法訪問更新的行數。
很高興在基本Groovy代碼中看到這種變化,或許有一個擴展點放在自己的處理程序中(因爲您不想在基本Groovy代碼中使用IBM特定的東西) ,但至少我現在有一個可行的解決方案。
public class SqlWithGeneratedKeys extends Sql {
public SqlWithGeneratedKeys(Sql parent) {
super(parent);
}
public List<GroovyRowResult> withBatch(String pSql, String [] keys, Closure closure) throws SQLException {
return this.withBatch(0, pSql, keys, closure);
}
public List<GroovyRowResult> withBatch(int batchSize, String pSql, String [] keys, Closure closure) throws SQLException {
final Connection connection = this.createConnection();
List<Tuple> indexPropList = null;
final SqlWithParams preCheck = this.buildSqlWithIndexedProps(pSql);
BatchingPreparedStatementWrapper psWrapper = null;
String sql = pSql;
if (preCheck != null) {
indexPropList = new ArrayList<Tuple>();
for (final Object next : preCheck.getParams()) {
indexPropList.add((Tuple) next);
}
sql = preCheck.getSql();
}
PreparedStatement statement = null;
try {
statement = connection.prepareStatement(sql, keys);
this.configure(statement);
psWrapper = new BatchingPreparedStatementWrapper(statement, indexPropList, batchSize, LOG, this);
closure.call(psWrapper);
psWrapper.executeBatch();
return this.getGeneratedKeys(statement);
} catch (final SQLException e) {
LOG.warning("Error during batch execution of '" + sql + "' with message: " + e.getMessage());
throw e;
} finally {
BaseDBServices.closeDBElements(connection, statement, null);
}
}
protected List<GroovyRowResult> getGeneratedKeys(Statement statement) throws SQLException {
if (statement instanceof DelegatingStatement) {
return this.getGeneratedKeys(DelegatingStatement.class.cast(statement).getDelegate());
} else if (statement instanceof DB2PreparedStatement) {
final ResultSet[] resultSets = DB2PreparedStatement.class.cast(statement).getDBGeneratedKeys();
final List<GroovyRowResult> keys = new ArrayList<GroovyRowResult>();
for (final ResultSet results : resultSets) {
while (results.next()) {
keys.add(SqlGroovyMethods.toRowResult(results));
}
}
return keys;
}
return Arrays.asList(SqlGroovyMethods.toRowResult(statement.getGeneratedKeys()));
}
}
調用它很好,很乾淨。
println new SqlWithGeneratedKeys(target).withBatch(statement, ['ISN'] as String[]) { ps ->
rows.each {
ps.addBatch(it)
}
}
當您打印'results'時出現什麼? –
所以我認爲在這裏有一些與我有關的事情.1)我們使用Apache的DBCP庫來管理我們的連接,並將準備好的語句包裝在DelegatingPreparedStatement類中。 2)'withBatch'中的SQL類不會創建具有所需額外參數的語句(http://docs.oracle.com/javase/7/docs/api/java/sql/Connection.html#prepareStatement(java) .lang.String,%20int [])),它將告訴JDBC返回生成的值。 –
它只是打印出類的名稱(DelegatingResultSet)。 –