Example usage for org.springframework.jdbc.object BatchSqlUpdate flush

List of usage examples for org.springframework.jdbc.object BatchSqlUpdate flush

Introduction

In this page you can find the example usage for org.springframework.jdbc.object BatchSqlUpdate flush.

Prototype

public int[] flush() 

Source Link

Document

Trigger any queued update operations to be added as a final batch.

Usage

From source file:anyframe.core.query.impl.QueryServiceImpl.java

/**
 * BatchSqlUpdate ? ? ? SQL?  Batch  .// w w  w  .ja  v  a2  s  .co m
 * 
 * @param sql
 *            query statement.
 * @param types
 *            is matched with input parameters. A type must belong to fields
 *            defined java.sql.Types package.
 * @param targets
 *            object of class which is matched with specified table in XML
 *            files. is the List type of Object Array.
 * @return an array of the number of rows affected by each statement.
 */
protected int[] batchExecutor(final String sql, int[] types, final List targets) throws QueryServiceException {
    if (targets.size() <= 0)
        throw new QueryServiceException(getMessageSource(), "error.query.runtime.batch");

    BatchSqlUpdate sqlBatch = new BatchSqlUpdate();
    sqlBatch.setJdbcTemplate(jdbcTemplate);
    sqlBatch.setSql(sql);

    for (int i = 0; types != null && i < types.length; i++) {
        SqlParameter sp = new SqlParameter(types[i]);
        sqlBatch.declareParameter(sp);
    }
    sqlBatch.compile();

    for (int i = 0; i < targets.size(); i++) {
        Object obj = targets.get(i);
        if (obj instanceof Object[])
            sqlBatch.update((Object[]) obj);
    }
    return sqlBatch.flush();
}

From source file:com.hmsinc.epicenter.tools.reclassifier.Reclassifier.java

@Transactional
public void run() {

    setup();//from   w  w  w .  j av a2  s.  c  o m

    final String destinationTable = (arguments.length > 4) ? arguments[4] : DEFAULT_TABLE_NAME;
    final String query = new StringBuilder("INSERT INTO ").append(destinationTable)
            .append(INSERT_CLASSIFICATION).toString();

    final BatchSqlUpdate updater = new BatchSqlUpdate(modelDataSource, query);
    updater.declareParameter(new SqlParameter(Types.BIGINT));
    updater.declareParameter(new SqlParameter(Types.BIGINT));
    updater.setBatchSize(BATCH_SIZE);
    updater.compile();

    final StatelessSession ss = ((Session) entityManager.getDelegate()).getSessionFactory()
            .openStatelessSession();

    final Criteria c = ss.createCriteria(target.getInteractionClass())
            .add(Restrictions.eq("patientClass", target.getPatientClass())).addOrder(Order.asc("id"))
            .setCacheable(false);

    if (arguments.length > 2) {
        c.add(Restrictions.gt("id", Long.valueOf(arguments[2])));
    }

    if (arguments.length > 3) {
        c.add(Restrictions.lt("id", Long.valueOf(arguments[3])));
    }

    final ScrollableResults sr = c.scroll(ScrollMode.FORWARD_ONLY);
    int i = 0;
    while (sr.next()) {

        final Interaction interaction = (Interaction) sr.get(0);
        final Set<Classification> classifications = classificationService.classify(interaction, target);

        save(interaction, classifications, updater);

        i++;
        if (i % BATCH_SIZE == 0) {
            logger.info("Processed {} interactions (current id: {})", i, interaction.getId());
        }

        ((Session) entityManager.getDelegate()).evict(interaction);
    }

    sr.close();

    updater.flush();
}

From source file:org.springframework.jdbc.object.BatchSqlUpdateTests.java

private void doTestBatchUpdate(boolean flushThroughBatchSize) throws Exception {
    final String sql = "UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = ?";
    final int[] ids = new int[] { 100, 200 };
    final int[] rowsAffected = new int[] { 1, 2 };

    MockControl ctrlPreparedStatement = MockControl.createControl(PreparedStatement.class);
    PreparedStatement mockPreparedStatement = (PreparedStatement) ctrlPreparedStatement.getMock();
    mockPreparedStatement.getConnection();
    ctrlPreparedStatement.setReturnValue(mockConnection);
    mockPreparedStatement.setObject(1, new Integer(ids[0]), Types.INTEGER);
    ctrlPreparedStatement.setVoidCallable();
    mockPreparedStatement.addBatch();//from www.jav  a2 s .c  o  m
    ctrlPreparedStatement.setVoidCallable();
    mockPreparedStatement.setObject(1, new Integer(ids[1]), Types.INTEGER);
    ctrlPreparedStatement.setVoidCallable();
    mockPreparedStatement.addBatch();
    ctrlPreparedStatement.setVoidCallable();
    mockPreparedStatement.executeBatch();
    ctrlPreparedStatement.setReturnValue(rowsAffected);
    if (debugEnabled) {
        mockPreparedStatement.getWarnings();
        ctrlPreparedStatement.setReturnValue(null);
    }
    mockPreparedStatement.close();
    ctrlPreparedStatement.setVoidCallable();

    MockControl ctrlDatabaseMetaData = MockControl.createControl(DatabaseMetaData.class);
    DatabaseMetaData mockDatabaseMetaData = (DatabaseMetaData) ctrlDatabaseMetaData.getMock();
    mockDatabaseMetaData.supportsBatchUpdates();
    ctrlDatabaseMetaData.setReturnValue(true);

    mockConnection.prepareStatement(sql);
    ctrlConnection.setReturnValue(mockPreparedStatement);
    mockConnection.getMetaData();
    ctrlConnection.setReturnValue(mockDatabaseMetaData, 1);

    ctrlPreparedStatement.replay();
    ctrlDatabaseMetaData.replay();
    replay();

    BatchSqlUpdate update = new BatchSqlUpdate(mockDataSource, sql);
    update.declareParameter(new SqlParameter(Types.INTEGER));
    if (flushThroughBatchSize) {
        update.setBatchSize(2);
    }

    update.update(ids[0]);
    update.update(ids[1]);

    if (flushThroughBatchSize) {
        assertEquals(0, update.getQueueCount());
        assertEquals(2, update.getRowsAffected().length);
    } else {
        assertEquals(2, update.getQueueCount());
        assertEquals(0, update.getRowsAffected().length);
    }

    int[] actualRowsAffected = update.flush();
    assertEquals(0, update.getQueueCount());

    if (flushThroughBatchSize) {
        assertTrue("flush did not execute updates", actualRowsAffected.length == 0);
    } else {
        assertTrue("executed 2 updates", actualRowsAffected.length == 2);
        assertEquals(rowsAffected[0], actualRowsAffected[0]);
        assertEquals(rowsAffected[1], actualRowsAffected[1]);
    }

    actualRowsAffected = update.getRowsAffected();
    assertTrue("executed 2 updates", actualRowsAffected.length == 2);
    assertEquals(rowsAffected[0], actualRowsAffected[0]);
    assertEquals(rowsAffected[1], actualRowsAffected[1]);

    update.reset();
    assertEquals(0, update.getRowsAffected().length);

    ctrlPreparedStatement.verify();
    ctrlDatabaseMetaData.verify();
}