1 package org.hibernate.jdbc; 3 4 import java.sql.PreparedStatement ; 5 import java.sql.SQLException ; 6 7 import org.hibernate.HibernateException; 8 import org.hibernate.StaleStateException; 9 10 15 public class BatchingBatcher extends AbstractBatcher { 16 17 private int batchSize; 18 private int[] expectedRowCounts; 19 20 public BatchingBatcher(ConnectionManager connectionManager) { 21 super( connectionManager ); 22 expectedRowCounts = new int[ getFactory().getSettings().getJdbcBatchSize() ]; 23 } 24 25 public void addToBatch(int expectedRowCount) throws SQLException , HibernateException { 26 27 log.trace("Adding to batch"); 28 PreparedStatement batchUpdate = getStatement(); 29 batchUpdate.addBatch(); 30 expectedRowCounts[ batchSize++ ] = expectedRowCount; 31 if ( batchSize==getFactory().getSettings().getJdbcBatchSize() ) { 32 doExecuteBatch(batchUpdate); 34 43 } 44 45 } 46 47 protected void doExecuteBatch(PreparedStatement ps) throws SQLException , HibernateException { 48 49 if (batchSize==0) { 50 log.debug("no batched statements to execute"); 51 } 52 else { 53 54 if ( log.isDebugEnabled() ) log.debug("Executing batch size: " + batchSize ); 55 56 try { 57 checkRowCounts( ps.executeBatch() ); 58 } 59 catch (RuntimeException re) { 60 log.error("Exception executing batch: ", re); 61 throw re; 62 } 63 finally { 64 batchSize=0; 65 } 67 68 } 69 70 } 71 72 private void checkRowCounts(int[] rowCounts) { 73 int rowCountLength = rowCounts.length; 74 if ( rowCountLength!=batchSize ) { 75 log.warn("JDBC driver did not return the expected number of row counts"); 76 } 77 for ( int i=0; i<rowCountLength; i++ ) { 78 checkRowCount( rowCounts[i], expectedRowCounts[i], i ); 79 } 80 } 81 82 private void checkRowCount(int rowCount, int expectedRowCount, int i) { 83 if ( rowCount==-2 ) { 84 if ( log.isDebugEnabled() ) log.debug("success of batch update unknown: " + i); 85 } 86 else if ( rowCount==-3 ) { 87 throw new HibernateException("Batch update failed: " + i); 88 } 89 else { 90 if ( expectedRowCount>=0 ) { 91 if ( rowCount<expectedRowCount ) { 92 throw new StaleStateException( 93 "Batch update returned unexpected row count from update: " + i + 94 " actual row count: " + rowCount + 95 " expected: " + expectedRowCount 96 ); 97 } 98 if ( rowCount>expectedRowCount ) { 99 throw new HibernateException( 100 "Batch update returned unexpected row count from update: " + i + 101 " actual row count: " + rowCount + 102 " expected: " + expectedRowCount 103 ); 104 } 105 } 106 } 107 } 108 109 } 110 111 112 113 114 115 116 | Popular Tags |