Example usage for org.springframework.jdbc.core JdbcTemplate query

List of usage examples for org.springframework.jdbc.core JdbcTemplate query

Introduction

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

Prototype

@Override
    public <T> List<T> query(PreparedStatementCreator psc, RowMapper<T> rowMapper) throws DataAccessException 

Source Link

Usage

From source file:com.javacreed.examples.spring.Example1.java

public static void main(final String[] args) throws Exception {
    final ComboPooledDataSource ds = DbUtils.createDs();
    try {/*from  ww w.j  av  a  2  s  .  c o m*/
        final JdbcTemplate jdbcTemplate = new JdbcTemplate(ds);

        Example1.LOGGER.debug("Reading all rows");
        final List<Data> rows = jdbcTemplate.query("SELECT * FROM `big_table`", Data.ROW_MAPPER);

        Example1.LOGGER.debug("All records read ({} records)", rows.size());

        // Sleep a bit so that it shows better on the profiler
        TimeUnit.SECONDS.sleep(10);
    } finally {
        DbUtils.closeQuietly(ds);
    }
    Example1.LOGGER.debug("Done");
}

From source file:com.javacreed.examples.spring.Example2.java

public static void main(final String[] args) throws Exception {
    final ComboPooledDataSource ds = DbUtils.createDs();
    try {//from  w  w w . ja  v  a2s.  c  o  m
        final JdbcTemplate jdbcTemplate = new JdbcTemplate(ds);

        Example2.LOGGER.debug("Reading all rows");
        final List<Data> rows = jdbcTemplate.query(new StreamingStatementCreator("SELECT * FROM `big_table`"),
                Data.ROW_MAPPER);

        Example2.LOGGER.debug("All records read ({} records)", rows.size());

        // Sleep a bit so that it shows better on the profiler
        TimeUnit.SECONDS.sleep(10);
    } finally {
        DbUtils.closeQuietly(ds);
    }
    Example2.LOGGER.debug("Done");
}

From source file:com.javacreed.examples.flyway.Example2.java

public static void main(final String[] args) {
    Example2.LOGGER.debug("Loading the spring context");
    try (ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
            "/META-INF/application-context.xml")) {
        final JdbcTemplate jdbcTemplate = context.getBean(JdbcTemplate.class);

        Example2.LOGGER.debug("Name      | Surname");
        Example2.LOGGER.debug("-----------------------");
        jdbcTemplate.query("SELECT * FROM `sample_table`", new RowCallbackHandler() {
            @Override/* w  w w.j ava2 s . co m*/
            public void processRow(final ResultSet resultSet) throws SQLException {
                Example2.LOGGER.debug(String.format("%-10s| %-10s", resultSet.getString("name"),
                        resultSet.getString("surname")));
            }
        });
        Example2.LOGGER.debug("-----------------------");
    }
}

From source file:com.kaidad.utilities.MBTilesBase64Converter.java

private static void encodeTileData(final JdbcTemplate c) {
    c.query("SELECT tile_id, tile_data FROM images", new ResultSetExtractor<Object>() {
        @Override//w  w  w  .  j  ava 2  s  . c  o m
        public Object extractData(ResultSet rs) throws SQLException, DataAccessException {
            while (rs.next()) {
                String tileId = rs.getString("tile_id");
                byte[] imageData = rs.getBytes("tile_data");
                addTileDataToStringTable(c, tileId, BaseEncoding.base64().encode(imageData));
            }
            System.out.println("Operation done successfully");
            return null;
        }
    });
}

From source file:com.acme.spring.jdbc.JdbcTestHelper.java

/**
 * <p>Retrieves all the stocks from database, using passed {@link JdbcTemplate}.</p>
 *
 * @param jdbcTemplate the jdbc template to use
 *
 * @return list of stocks retrieved from database
 *///from   w  w w .j a v  a2s  .c o  m
public static List<Stock> retrieveAllStocks(JdbcTemplate jdbcTemplate) {

    return jdbcTemplate.query("select id, name, symbol, value, date from Stock order by name",
            new RowMapper<Stock>() {
                public Stock mapRow(ResultSet rs, int rowNum) throws SQLException {

                    int index = 1;

                    Stock result = new Stock();
                    result.setId(rs.getLong(index++));
                    result.setName(rs.getString(index++));
                    result.setSymbol(rs.getString(index++));
                    result.setValue(rs.getBigDecimal(index++));
                    result.setDate(rs.getDate(index++));

                    return result;
                }
            });
}

From source file:com.ineunet.knife.persist.PersistUtils.java

public static boolean existsTable(final String tableName, JdbcTemplate jdbcTemplate) {
    return jdbcTemplate.query("show tables", new ResultSetExtractor<Boolean>() {
        @Override/*from   w  ww. j a  va 2 s  . c om*/
        public Boolean extractData(ResultSet rs) throws SQLException, DataAccessException {
            while (rs.next()) {
                String tableNameOther = rs.getString(1);
                if (tableName.equalsIgnoreCase(tableNameOther))
                    return true;
            }
            return false;
        }
    });
}

From source file:org.paxml.util.PaxmlUtils.java

public static long getNextExecutionId() {
    if (true) {//from  w ww.  j av a 2 s  .  c  o  m
        return -1;
    }
    JdbcTemplate temp = new JdbcTemplate(DBUtils.getPooledDataSource());
    return temp.query("select next value for execution_id_seq", new ResultSetExtractor<Long>() {

        @Override
        public Long extractData(ResultSet rs) throws SQLException, DataAccessException {
            rs.next();
            return rs.getLong(1);
        }

    });
}

From source file:net.firejack.platform.core.utils.db.DBUtils.java

/**
 * @param sql//from   w  ww.  j av  a 2 s.  c o  m
 * @param dataSource
 * @param rsExtractor
 * @return
 * @throws CommonDBAccessException
 */
public static <T> T query(String sql, DataSource dataSource, ResultSetExtractor<T> rsExtractor)
        throws CommonDBAccessException {
    JdbcTemplate template = new JdbcTemplate(dataSource);
    try {
        return template.query(sql, rsExtractor);
    } catch (DataAccessException e) {
        logger.error(e.getMessage(), e);
        throw new CommonDBAccessException(e);
    }
}

From source file:net.firejack.platform.core.utils.db.DBUtils.java

/**
 * @param sql/*  w w  w  .j ava  2s. c  om*/
 * @param dataSource
 * @param rowMapper
 * @return
 * @throws CommonDBAccessException
 */
public static <T> List<T> query(String sql, DataSource dataSource, RowMapper<T> rowMapper)
        throws CommonDBAccessException {
    JdbcTemplate template = new JdbcTemplate(dataSource);
    try {
        return template.query(sql, rowMapper);
    } catch (DataAccessException e) {
        logger.error(e.getMessage(), e);
        throw new CommonDBAccessException(e);
    }
}

From source file:com.alibaba.otter.shared.common.utils.meta.DdlUtils.java

/**
 * !!! Only supports MySQL/* w w w .  ja  v a 2 s  . c  o m*/
 */
@SuppressWarnings("unchecked")
public static List<String> findSchemas(JdbcTemplate jdbcTemplate, final String schemaPattern) {
    try {
        if (StringUtils.isEmpty(schemaPattern)) {
            return jdbcTemplate.query("show databases", new SingleColumnRowMapper(String.class));
        }
        return jdbcTemplate.query("show databases like ?", new Object[] { schemaPattern },
                new SingleColumnRowMapper(String.class));
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        return new ArrayList<String>();
    }
}