2010-09-20 12 views
9

Myślę, że to musi być łatwe. Musi istnieć jakaś metoda. Oto, czego chcę: -Jak uzyskać liczbę partii w przygotowaniu?

PreparedStatement ps = ... 
ps.addBatch (); 
ps.addBatch (); 
ps.addBatch (); 
logger.info ("totalBatches: " + ps.someMethod()); 
ps.executeBatch (); 

efekt będzie następujący: ogółem: 3;
Jeśli nie ma takiej metody, to jak to zrobić?

Odpowiedz

6

Ta funkcja nie jest obsługiwana. Ale możesz zawrzeć Oświadczenie i zastąpić addBatch() przez dodanie członka liczącego. Jeśli używasz Apache Commons DBCP, możesz dziedziczyć po DelegatingPreparedStatement, w przeciwnym razie masz brak opakowania dla PreparedStatement. Więc użyłem proxy, aby dodać metodę:

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(); 
    } 
} 
3

executeBatch zwróci tablicę liczb całkowitych. Po prostu weź długość tablicy.

Jeśli potrzebujesz liczby partii przed jej wykonaniem, to domyślam się, że jedynym obejściem jest policzenie go za każdym razem, ilekroć addBatch został wywołany.

+3

Myślę, że Rakesh chciałby uzyskać liczbę partii przed egzekucją. W przeciwnym razie użycie executeBatch jest OK. – rics

Powiązane problemy