这不是最优雅的解决方案,您将付出 %$# 的性能,但它确实有效。
public class DBEngine {
private final int defaultBatchSize = 1000;
private Pool pool = null;
private Connection con = null;
private PreparedStatement ps = null;
private ArrayList<PreparedStatement> globalBatch = new ArrayList<PreparedStatement>();
private int k = 0; //bean-wide batch counter
private boolean debugMode = false;
private PreparedStatement batchPs = null;
//--------------------------------
DBEngine(){
this.pool = new Pool();
this.con = pool.getConnection();
this.ps = null;
this.k = 0; //bean-wide batch counter
}
//-------------
boolean mixedBatchTime(boolean force){
return mixedBatchTime(defaultBatchSize, force);
}
//-------------
boolean mixedBatchTime(int customBatchSize){
return mixedBatchTime(customBatchSize, false);
}
//-------------
boolean mixedBatchTime(){
return mixedBatchTime(defaultBatchSize, false);
}
//-------------
// Executes a mixed batch of PreparedStatements
//-------------
boolean mixedBatchTime(int customBatchSize, boolean force){
if(k > customBatchSize - 1 || force){
try {
StringBuilder sqlStmt = new StringBuilder();
for(int i = 0; i < globalBatch.size(); i++){
sqlStmt.append(globalBatch.get(i) + "; ");
}
batchPs = con.prepareStatement(sqlStmt.toString());
batchPs.execute();
ps = null;
sqlStmt = null;
batchPs = null;
} catch (SQLException e) {
e.printStackTrace();
}
k = 0;
globalBatch = null;
globalBatch = new ArrayList<PreparedStatement>();
return true;
}else return false;
}
}
您必须在DBEngine bean 内部的实际批处理准备部分中增加 k,例如:
//------------------------------------------
boolean updateSomeQuantity(int someID, int someQuantity){
try{
// detects if the statement has changed in order to recompile it only once per change
if(ps!=null && !ps.toString().contains("UPDATE sometable SET somequantity =")){
ps = null;
String updateStmt = "UPDATE sometable SET somequantity = ? WHERE someID = ?";
ps = con.prepareStatement(updateStmt);
}else if(ps == null){
String updateStmt = "UPDATE sometable SET somequantity = ? WHERE someID = ?";
ps = con.prepareStatement(updateStmt);
}
ps.setInt(1, someQuantity)
ps.setInt(2, someID);
globalBatch.add(ps);
k++; // very important
return true;
} catch (SQLException e) {
e.printStackTrace();
if(e.getNextException() != null) e.getNextException().printStackTrace();
return false;
}
}
实际实现在另一个代码中,您在其中实例化 DBEngine bean 的实例并在循环中使用 updateSomeQuantity(somequantity) 方法和 mixedBatchTime() 方法。循环完成后,调用mixedBatchTime(true) 对剩余的任何内容进行批处理。
注意:此解决方案使用 AutoCommit(true)