I think this must be easy. There must be some method for this. This is what i want:-
PreparedStatement ps = ...
ps.addBatch ( );
ps.addBatch ( );
ps.addBatch ( );
logger.info ( "totalBatches: " + ps.someMethod() );
ps.executeBatch ( );
result will be: totalbatches: 3;
If there is no such method then how to do this?
This functionality is not supported. But you can wrap the Statement and override addBatch() by adding a counting member. If using Apache Commons DBCP, you can inherit from DelegatingPreparedStatement
, else you have a lack of a wrapper for PreparedStatement
. So I used a proxy to add the method:
public class BatchCountingStatementHandler implements InvocationHandler {
public static BatchCountingStatement countBatches(PreparedStatement delegate) {
return Proxy.newProxyInstance(delegate.getClassLoader(), new Class[] {BatchCountingStatement.class}, new BatchCountingStatementHandler(delegate));
}
private final PreparedStatement delegate;
private int count = 0;
private BatchCountingStatementHandler(PreparedStatement delegate) {
this.delegate = delegate;
}
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
if ("getBatchCount".equals(method.getName())) {
return count;
}
try {
return method.invoke(delegate, args);
} finally {
if ("addBatch".equals(method.getName())) {
++count;
}
}
}
public static interface BatchCountingStatement extends PreparedStatement {
public int getBatchCount();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With