Example usage for org.springframework.jdbc.core.namedparam SqlParameterSourceUtils createBatch

List of usage examples for org.springframework.jdbc.core.namedparam SqlParameterSourceUtils createBatch

Introduction

In this page you can find the example usage for org.springframework.jdbc.core.namedparam SqlParameterSourceUtils createBatch.

Prototype

public static SqlParameterSource[] createBatch(Map<String, ?>[] valueMaps) 

Source Link

Document

Create an array of MapSqlParameterSource objects populated with data from the values passed in.

Usage

From source file:ar.com.springbasic.dao.AdminDaoImpl.java

@Transactional
@Override/* w  ww . j a  va 2  s.com*/
public int[] saveAll(List<Admin> admins) {
    SqlParameterSource[] batchArgs = SqlParameterSourceUtils.createBatch(admins.toArray());
    return jdbcTemplate.batchUpdate(
            "insert into springbd.admin (nombre, cargo, fechaCreacion) values (:nombre, :cargo, :fechaCreacion)",
            batchArgs);
}

From source file:com.mesut.daopattern.OffersDAO.java

public int[] createOffers(List<Offer> offers) {
    SqlParameterSource[] params = SqlParameterSourceUtils.createBatch(offers.toArray());
    return jdbc.batchUpdate("insert into offers (name, email, text) values(:name, :email, :text)", params);
}

From source file:dao.BankDao.java

public int[] updateDB(List<Bank> banks) {

    logger.info("run");

    SqlParameterSource[] resBatch = SqlParameterSourceUtils.createBatch(banks.toArray());

    int[] res = jdbc.batchUpdate(
            "INSERT INTO banktable (name, code, mfo, date, adress, license, licensedate, status, shortName) VALUES (:name, :code, :mfo, :date, :adress, :license, :licensedate, :status, :shortName)",
            resBatch);/*from  w  ww.j a  va2s .  c o  m*/
    return res;
}

From source file:com.zonekey.ssm.common.log.appender.JdbcLogWriter.java

/**
 * Buffer???.//from www  .  j  ava2  s  . co m
 */
@SuppressWarnings("unchecked")
public void updateBatch() {
    try {
        // ?, ?jdbc??.
        int i = 0;
        Map[] paramMapArray = new HashMap[eventsBuffer.size()];
        for (LoggingEvent event : eventsBuffer) {
            paramMapArray[i++] = parseEvent(event);
        }
        final SqlParameterSource[] batchParams = SqlParameterSourceUtils.createBatch(paramMapArray);

        // ??,?.
        transactionTemplate.execute(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(TransactionStatus status) {
                try {
                    jdbcTemplate.batchUpdate(getActualSql(), batchParams);
                    if (logger.isDebugEnabled()) {
                        for (LoggingEvent event : eventsBuffer) {
                            logger.debug("saved event: {}", new LoggingEventWrapper(event).convertToString());
                        }
                    }
                } catch (DataAccessException e) {
                    status.setRollbackOnly();
                    handleDataAccessException(e, eventsBuffer);
                }
            }
        });

        // ?Buffer
        eventsBuffer.clear();
    } catch (Exception e) {
        logger.error("????.", e);
    }
}

From source file:org.springside.examples.showcase.log.appender.JdbcLogWriter.java

/**
 * Buffer???.//from  w  ww .j a  va 2s . c  o  m
 */
@SuppressWarnings("unchecked")
public void updateBatch() {
    try {
        //?, ?jdbc??.
        int i = 0;
        Map[] paramMapArray = new HashMap[eventsBuffer.size()];
        for (LoggingEvent event : eventsBuffer) {
            paramMapArray[i++] = parseEvent(event);
        }
        final SqlParameterSource[] batchParams = SqlParameterSourceUtils.createBatch(paramMapArray);

        //??,?.
        transactionTemplate.execute(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(TransactionStatus status) {
                try {
                    jdbcTemplate.batchUpdate(getActualSql(), batchParams);
                    if (logger.isDebugEnabled()) {
                        for (LoggingEvent event : eventsBuffer) {
                            logger.debug("saved event: {}", new LoggingEventWrapper(event).convertToString());
                        }
                    }
                } catch (DataAccessException e) {
                    status.setRollbackOnly();
                    handleDataAccessException(e, eventsBuffer);
                }
            }
        });

        //?Buffer
        eventsBuffer.clear();
    } catch (Exception e) {
        logger.error("????.", e);
    }
}

From source file:com.seovic.coherence.util.persistence.AbstractJdbcCacheStore.java

/**
 * {@inheritDoc}/*from w ww .ja v  a 2s .  c o  m*/
 */
public void storeBatch(Map mapBatch) {
    SqlParameterSource[] batch = SqlParameterSourceUtils.createBatch(mapBatch.values().toArray());

    getJdbcTemplate().batchUpdate(getMergeSql(), batch);
}

From source file:org.semispace.semimeter.dao.jdbc.SemiMeterDaoJdbc.java

public void performInsertion(Collection<Item> items) {
    //log.debug("Performing batch insertion of "+items.size()+" items.");
    SqlParameterSource[] insertArgs = SqlParameterSourceUtils.createBatch(items.toArray());
    List<Object[]> updateArgs = new ArrayList<Object[]>();

    for (Item item : items) {
        // Original just called insert
        updateArgs.add(new Object[] { item.getAccessNumber(), item.getPath(), item.getWhen() });
    }//  www.  ja  v  a2s.c  o m
    rwl.writeLock().lock();
    try {
        try {
            //log.debug("INSERT INTO meter(updated, count, path) SELECT DISTINCT ?, 0, ? FROM meter WHERE NOT EXISTS ( SELECT * FROM meter WHERE updated=? AND path=?)");
            jdbcTemplate.batchUpdate(
                    "INSERT INTO meter(updated, counted, path) SELECT :when, 0, :path FROM meter WHERE NOT EXISTS ( SELECT * FROM meter WHERE updated=:when AND path=:path) LIMIT 1",
                    insertArgs);

        } catch (Exception e) {
            log.warn(
                    "Unlikely event occurred - failure whilst inserting priming elements. This is not overly critical. Masked exception: "
                            + e);
        }
        jdbcTemplate.batchUpdate("update meter SET counted=counted+? WHERE path like ? and updated=?",
                updateArgs);
    } catch (Exception e) {
        log.error("Could not update elements", e);
    } finally {
        rwl.writeLock().unlock();
    }
}

From source file:org.jasig.schedassist.impl.relationship.CSVRelationshipDataSourceImpl.java

/**
 * This method deletes all existing rows from the isis_records table, then invokes
 * {@link #batchLoadData(Resource)} to refresh it.
 * //from   w  ww . j  av  a 2  s  . c  om
 * This method is marked with Spring's {@link Transactional} annotation, and if
 * the Scheduling Assistant application is running should only be executed when transactional 
 * support is available.
 * 
 * @see Transactional
 * @param resource
 * @throws IOException
 */
@Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRES_NEW)
public synchronized void reloadData() {
    final String propertyValue = System.getProperty("org.jasig.schedassist.runScheduledTasks", "true");
    if (Boolean.parseBoolean(propertyValue)) {
        if (isResourceUpdated(csvResource)) {
            LOG.info("resource updated, reloading advisorList data");
            //List<StudentAdvisorAssignment> records = readResource(advisorListResource, currentTerm);
            List<CSVRelationship> records = new ArrayList<CSVRelationship>();
            try {
                records = readCSVResource(csvResource);
            } catch (IOException e) {
                LOG.error("caught IOException reading csv data source", e);
                return;
            }

            if (records.isEmpty()) {
                LOG.warn("resource returned empty set, skipping reloadData");
                return;
            }

            LOG.info("deleting all existing records from csv_relationships table");
            StopWatch stopWatch = new StopWatch();
            stopWatch.start();
            this.getJdbcTemplate().execute("delete from csv_relationships");
            long deleteTime = stopWatch.getTime();
            LOG.info("finished deleting existing (" + deleteTime + " msec), starting batch insert");
            stopWatch.reset();
            stopWatch.start();
            SqlParameterSource[] batch = SqlParameterSourceUtils.createBatch(records.toArray());
            this.getSimpleJdbcTemplate().batchUpdate(
                    "insert into csv_relationships (owner_id, visitor_id, rel_description) values (:ownerIdentifier, :visitorIdentifier, :relationshipDescription)",
                    batch);
            long insertTime = stopWatch.getTime();
            stopWatch.stop();
            LOG.info("batch insert complete (" + insertTime + " msec)");
            LOG.info("reloadData complete (total time: " + (insertTime + deleteTime) + " msec)");
            this.lastReloadTimestamp = new Date();
            try {
                this.resourceLastModified = csvResource.lastModified();
            } catch (IOException e) {
                LOG.debug("ignoring IOException from accessing Resource.lastModified()");
            }
        } else {
            LOG.info("resource not modified since last reload, skipping");
        }
    } else {
        LOG.debug("ignoring reloadData as 'org.jasig.schedassist.runScheduledTasks' set to false");
    }
}

From source file:org.semispace.semimeter.dao.SemiMeterDao.java

protected void performInsertion(Collection<Item> items) {
    //log.debug("Performing batch insertion of "+items.size()+" items.");
    SqlParameterSource[] insertArgs = SqlParameterSourceUtils.createBatch(items.toArray());
    List<Object[]> updateArgs = new ArrayList<Object[]>();

    for (Item item : items) {
        // Original just called insert
        updateArgs.add(new Object[] { item.getAccessNumber(), item.getPath(), item.getWhen() });
    }/*from w  w w .  jav a2  s. com*/
    rwl.writeLock().lock();
    try {
        try {
            //log.debug("INSERT INTO meter(updated, count, path) SELECT DISTINCT ?, 0, ? FROM meter WHERE NOT EXISTS ( SELECT * FROM meter WHERE updated=? AND path=?)");
            jdbcTemplate.batchUpdate(
                    "INSERT INTO meter(updated, counted, path) SELECT DISTINCT :when, 0, :path FROM meter WHERE NOT EXISTS ( SELECT * FROM meter WHERE updated=:when AND path=:path)",
                    insertArgs);
        } catch (Exception e) {
            log.warn(
                    "Unlikely event occurred - failure whilst inserting priming elements. This is not overly critical. Masked exception: "
                            + e);
        }
        jdbcTemplate.batchUpdate("update meter SET counted=counted+? WHERE path like ? and updated=?",
                updateArgs);
    } catch (Exception e) {
        log.error("Could not update elements", e);
    } finally {
        rwl.writeLock().unlock();
    }
}

From source file:org.semispace.semimeter.dao.SemiMeterDao.java

private void failed_rewrite_performInsertion(Collection<Item> items) {
    //log.debug("Performing batch insertion of "+items.size()+" items.");
    //List<Object[]> insertArgs = new ArrayList<Object[]>();
    //List<Object[]> updateArgs = new ArrayList<Object[]>();

    SqlParameterSource[] insertArgs = SqlParameterSourceUtils.createBatch(items.toArray());
    SqlParameterSource[] updateArgs = SqlParameterSourceUtils.createBatch(items.toArray());

    //for ( Item item : items ) {
    // Original just called insert
    //insertArgs.add( new Object[]{item.getWhen(), item.getPath(),item.getWhen(), item.getPath()});
    //updateArgs.add( new Object[] {item.getAccessNumber(), item.getPath(), item.getWhen()});
    //}/* w  ww  .j a  v a2  s.  co  m*/
    rwl.writeLock().lock();
    try {
        try {
            //log.debug("INSERT INTO meter(updated, count, path) SELECT DISTINCT ?, 0, ? FROM meter WHERE NOT EXISTS ( SELECT * FROM meter WHERE updated=? AND path=?)");
            jdbcTemplate.batchUpdate(
                    "INSERT INTO meter(updated, counted, path) SELECT DISTINCT :when, 0, :path FROM meter WHERE NOT EXISTS ( SELECT * FROM meter WHERE updated=:when AND path=:path)",
                    insertArgs);
        } catch (Exception e) {
            log.warn(
                    "Unlikely event occurred - failure whilst inserting priming elements. This is not overly critical. Masked exception: "
                            + e);
        }
        jdbcTemplate.batchUpdate(
                "update meter SET counted=counted+:accessNumber WHERE :path like :path and updated=:when",
                updateArgs);
    } catch (Exception e) {
        log.error("Could not update elements", e);
    } finally {
        rwl.writeLock().unlock();
    }
}