Example usage for org.springframework.jdbc.core BatchPreparedStatementSetter BatchPreparedStatementSetter

List of usage examples for org.springframework.jdbc.core BatchPreparedStatementSetter BatchPreparedStatementSetter

Introduction

In this page you can find the example usage for org.springframework.jdbc.core BatchPreparedStatementSetter BatchPreparedStatementSetter.

Prototype

BatchPreparedStatementSetter

Source Link

Usage

From source file:wiki.doc.DocResource.java

public static void insertAll(final List<Doc> docs, DbConnector dbc) {
    BatchPreparedStatementSetter bpss = new BatchPreparedStatementSetter() {
        @Override/*  ww  w.ja  va  2 s  .c  o m*/
        public void setValues(PreparedStatement preparedStatement, int i) throws SQLException {
            preparedStatement.setString(1, docs.get(i).title);
            preparedStatement.setLong(2, docs.get(i).id);
        }

        @Override
        public int getBatchSize() {
            return docs.size();
        }
    };

    dbc.jdbcTemplate.batchUpdate("INSERT INTO pages(title, id) values(?, ?)", bpss);
}

From source file:lcn.module.batch.web.guide.support.StagingItemWriter.java

/**
 * BATCH_STAGING? write//  ww  w  .  j  av a 2 s. c o  m
 */
public void write(final List<? extends T> items) {

    final ListIterator<? extends T> itemIterator = items.listIterator();
    getJdbcTemplate().batchUpdate("INSERT into BATCH_STAGING (ID, JOB_ID, VALUE, PROCESSED) values (?,?,?,?)",
            new BatchPreparedStatementSetter() {

                public int getBatchSize() {
                    return items.size();
                }

                public void setValues(PreparedStatement ps, int i) throws SQLException {

                    long id = incrementer.nextLongValue();
                    long jobId = stepExecution.getJobExecution().getJobId();

                    Assert.state(itemIterator.nextIndex() == i,
                            "Item ordering must be preserved in batch sql update");

                    byte[] blob = SerializationUtils.serialize((Serializable) itemIterator.next());

                    ps.setLong(1, id);
                    ps.setLong(2, jobId);
                    ps.setBytes(3, blob);
                    ps.setString(4, NEW);
                }
            });

}

From source file:com.ccoe.build.tracking.jdbc.SessionJDBCTemplate.java

public int[] batchUpdateCategory(final List<Session> sessions) {
    int[] updateCounts = jdbcTemplateObject.batchUpdate(
            "update RBT_SESSION set category = ?,  filter = ? where id = ?",
            new BatchPreparedStatementSetter() {
                public void setValues(PreparedStatement ps, int i) throws SQLException {
                    ps.setString(1, sessions.get(i).getCategory());
                    ps.setString(2, sessions.get(i).getFilter());
                    ps.setInt(3, sessions.get(i).getId());
                }/*from w  w  w . ja va2  s  .co m*/

                public int getBatchSize() {
                    return sessions.size();
                }
            });
    return updateCounts;
}

From source file:org.gridobservatory.greencomputing.dao.TimeseriesDao.java

protected void insertTimeSeriesAcquisitions(final BigInteger timeSeriesId,
        final List<TimeseriesAcquisitionType> acquisitions) {
    executor.submit(new Runnable() {
        @Override//w  w  w. j a  v  a 2s  .  com
        public void run() {
            if (acquisitions != null) {
                getJdbcTemplate().batchUpdate(
                        "insert into time_series_acquisition (time_series_id, ts, value) values (?,?,?)",
                        new BatchPreparedStatementSetter() {

                            @Override
                            public void setValues(PreparedStatement ps, int i) throws SQLException {
                                ps.setLong(1, timeSeriesId.longValue());
                                long dateInMilis = acquisitions.get(i).getTs()
                                        .multiply(BigInteger.valueOf(1000l)).longValue();
                                ps.setTimestamp(2, new Timestamp(dateInMilis));
                                ps.setBigDecimal(3, new BigDecimal(acquisitions.get(i).getV()));
                            }

                            @Override
                            public int getBatchSize() {
                                return acquisitions.size();
                            }
                        });
            }
        }
    });
}

From source file:net.duckling.ddl.service.resource.dao.StarmarkDAOImpl.java

@Override
public int batchCreate(final String uid, final int tid, final List<Long> rids) {
    this.getJdbcTemplate().batchUpdate(SQL_CREATE, new BatchPreparedStatementSetter() {

        @Override/*ww w.jav  a2s .c  o m*/
        public int getBatchSize() {
            return (null == rids || rids.isEmpty()) ? 0 : rids.size();
        }

        @Override
        public void setValues(PreparedStatement ps, int index) throws SQLException {
            int i = 0;
            long rid = rids.get(index);
            ps.setInt(++i, (int) rid);
            ps.setInt(++i, tid);
            ps.setString(++i, uid);
            ps.setTimestamp(++i, new Timestamp((new Date()).getTime()));
        }

    });
    return 1;
}

From source file:com.laxser.blitz.lama.provider.jdbc.JdbcImpl.java

@Override
public int[] batchUpdate(Modifier modifier, String sql, final List<Object[]> args) throws DataAccessException {
    if (logger.isDebugEnabled()) {
        logger.debug("Executing SQL batch update [" + sql + "]");
    }// w w  w.  j a v a2s.  c  o  m

    return spring.batchUpdate(sql, new BatchPreparedStatementSetter() {

        @Override
        public void setValues(PreparedStatement ps, int i) throws SQLException {
            Object[] values = args.get(i);
            for (int j = 0; j < values.length; j++) {
                Object arg = values[j];
                if (arg instanceof SqlParameterValue) {
                    SqlParameterValue paramValue = (SqlParameterValue) arg;
                    StatementCreatorUtils.setParameterValue(ps, j + 1, paramValue, paramValue.getValue());
                } else {
                    StatementCreatorUtils.setParameterValue(ps, j + 1, SqlTypeValue.TYPE_UNKNOWN, arg);
                }
            }
        }

        @Override
        public int getBatchSize() {
            return args.size();
        }
    });
}

From source file:com.sinet.gage.dao.DomainsRepository.java

/**
 * //from   w  ww. j ava 2 s .  co m
 * @param domains
 */
public void insertDomains(List<Domain> domains) {
    try {
        jdbcTemplate.batchUpdate(DOMAINS_INSERT_SQL, new BatchPreparedStatementSetter() {

            public int getBatchSize() {
                if (domains == null)
                    return 0;
                return domains.size();
            }

            @Override
            public void setValues(PreparedStatement ps, int i) throws SQLException {
                Domain domain = domains.get(i);
                ps.setLong(1, domain.getDomainId());
                ps.setObject(2, domain.getGuid());
                ps.setString(3, domain.getDomainName());
                ps.setString(4, domain.getLoginPrefix());
                ps.setLong(5, domain.getFlag());
                ps.setString(6, domain.getDomainType());
                ps.setLong(7, domain.getParentDomainId());
                ps.setString(8, domain.getParentDomainName());
                ps.setLong(9, domain.getStateDomainId());
                ps.setString(10, domain.getStateDomainName());
                ps.setString(11, domain.getLicenseType());
                ps.setString(12, domain.getLicensePoolType());
                ps.setInt(13, domain.getNoOfLicense());
                ps.setBoolean(14, domain.isPilot());
                ps.setDate(15, domain.getPilotStartDate());
                ps.setDate(16, domain.getPilotEndDate());
                ps.setBoolean(17, domain.isFullSubscription());
                ps.setObject(18, domain.getSubscriptionStartDate());
                ps.setObject(19, domain.getSubscriptionEndDate());
                ps.setLong(20, domain.getCreatorUserId());
                ps.setTimestamp(21, domain.getCreationDate());
                ps.setLong(22, domain.getModifierUserId());
                ps.setTimestamp(23, domain.getModifiedDate());
            }
        });
    } catch (Exception e) {
        log.error("Error in inserting Domains", e);
    }
}

From source file:gov.nih.nci.cabig.caaers.dao.MedDRADao.java

/**
 * This method populats the meddra_pt table. It uses the file meddra_pt.asc to load data into this table. Different sqls are used
 * for postgres and oracle db.//  w  w  w  .j a  v  a2  s  .co  m
 * 
 * @param llts
 * @param startIndex
 * @return
 */
public int[] insertPreferredTerms(final List llts, final int startIndex, final int version_id,
        final Map<String, Integer> codeToIdMap) {

    String sql = "insert into meddra_pt (meddra_code,meddra_term,meddra_soc_id,version_id) "
            + "values (?,?,?,?)";

    String dataBase = "";
    if (properties.getProperty(DB_NAME) != null) {
        dataBase = properties.getProperty(DB_NAME);
    }
    if (dataBase.equals(ORACLE_DB))
        sql = "insert into meddra_pt (id,meddra_code,meddra_term,meddra_soc_id,version_id) "
                + "values (SEQ_MEDDRA_PT_ID.NEXTVAL,?,?,?,?)";

    BatchPreparedStatementSetter setter = null;
    setter = new BatchPreparedStatementSetter() {

        public int getBatchSize() {
            return llts.size();
        }

        public void setValues(PreparedStatement ps, int index) throws SQLException {
            String[] llt = (String[]) llts.get(index);
            ps.setString(1, llt[0]);
            ps.setString(2, llt[1]);
            if (codeToIdMap.containsKey(llt[3]))
                ps.setInt(3, (codeToIdMap.get(llt[3]).intValue()));
            else
                ps.setInt(3, 0);
            ps.setInt(4, version_id);
        }
    };

    return jdbcTemplate.batchUpdate(sql, setter);
}

From source file:com.alibaba.otter.node.etl.common.db.DbPerfIntergration.java

@Test
public void test_stack() {
    DbMediaSource dbMediaSource = new DbMediaSource();
    dbMediaSource.setId(1L);//w w w . j a  v  a  2s .  c  o  m
    dbMediaSource.setDriver("com.mysql.jdbc.Driver");
    dbMediaSource.setUsername("otter");
    dbMediaSource.setPassword("otter");
    dbMediaSource.setUrl("jdbc:mysql://127.0.0.1:3306/retl");
    dbMediaSource.setEncode("UTF-8");
    dbMediaSource.setType(DataMediaType.MYSQL);

    DbDataMedia dataMedia = new DbDataMedia();
    dataMedia.setSource(dbMediaSource);
    dataMedia.setId(1L);
    dataMedia.setName("ljhtable1");
    dataMedia.setNamespace("otter");

    final DbDialect dbDialect = dbDialectFactory.getDbDialect(2L, dataMedia.getSource());
    want.object(dbDialect).clazIs(MysqlDialect.class);

    final TransactionTemplate transactionTemplate = dbDialect.getTransactionTemplate();

    // ??
    int minute = 5;
    int nextId = 1;
    final int thread = 10;
    final int batch = 50;
    final String sql = "insert into otter.ljhtable1 values(? , ? , ? , ?)";

    final CountDownLatch latch = new CountDownLatch(thread);
    ExecutorService executor = new ThreadPoolExecutor(thread, thread, 60, TimeUnit.SECONDS,
            new ArrayBlockingQueue(thread * 2), new NamedThreadFactory("load"),
            new ThreadPoolExecutor.CallerRunsPolicy());

    for (int sec = 0; sec < minute * 60; sec++) {
        // 
        long startTime = System.currentTimeMillis();
        for (int i = 0; i < thread; i++) {
            final int start = nextId + i * batch;
            executor.submit(new Runnable() {

                public void run() {
                    try {
                        transactionTemplate.execute(new TransactionCallback() {

                            public Object doInTransaction(TransactionStatus status) {
                                JdbcTemplate jdbcTemplate = dbDialect.getJdbcTemplate();
                                return jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {

                                    public void setValues(PreparedStatement ps, int idx) throws SQLException {
                                        int id = start + idx;
                                        StatementCreatorUtils.setParameterValue(ps, 1, Types.INTEGER, null, id);
                                        StatementCreatorUtils.setParameterValue(ps, 2, Types.VARCHAR, null,
                                                RandomStringUtils.randomAlphabetic(1000));
                                        // RandomStringUtils.randomAlphabetic()
                                        long time = new Date().getTime();
                                        StatementCreatorUtils.setParameterValue(ps, 3, Types.TIMESTAMP,
                                                new Timestamp(time));
                                        StatementCreatorUtils.setParameterValue(ps, 4, Types.TIMESTAMP,
                                                new Timestamp(time));
                                    }

                                    public int getBatchSize() {
                                        return batch;
                                    }
                                });
                            }
                        });
                    } finally {
                        latch.countDown();
                    }
                }
            });

        }

        long endTime = System.currentTimeMillis();
        try {
            latch.await(1000 * 60L - (endTime - startTime), TimeUnit.MILLISECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        if (latch.getCount() != 0) {
            System.out.println("perf is not enough!");
            System.exit(-1);
        }
        endTime = System.currentTimeMillis();
        System.out.println("Time cost : " + (System.currentTimeMillis() - startTime));
        try {
            TimeUnit.MILLISECONDS.sleep(1000L - (endTime - startTime));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        nextId = nextId + thread * batch;
    }
    executor.shutdown();
}

From source file:net.duckling.ddl.service.resource.dao.TagItemDAOImpl.java

@Override
public int batchUpdateWithTag(final int tid, final int tagid, final List<Long> rids) {
    this.getJdbcTemplate().batchUpdate(SQL_CREATE, new BatchPreparedStatementSetter() {

        @Override//  w ww  .j  ava  2 s  .c om
        public int getBatchSize() {
            return (null == rids || rids.size() <= 0) ? 0 : rids.size();
        }

        @Override
        public void setValues(PreparedStatement ps, int index) throws SQLException {
            long rid = rids.get(index);
            int i = 0;
            ps.setInt(++i, tid);
            ps.setInt(++i, tagid);
            ps.setInt(++i, (int) rid);
            ps.setInt(++i, tid);
            ps.setInt(++i, tagid);
            ps.setInt(++i, (int) rid);
        }

    });
    return 1;
}