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

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

Introduction

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

Prototype

RowCallbackHandler

Source Link

Usage

From source file:com.cnd.greencube.server.dao.jdbc.JdbcDAO.java

@SuppressWarnings("rawtypes")
public List queryExt(String sql) {
    final List lstValue = new ArrayList();
    getJdbcTemplate().query(sql, new RowCallbackHandler() {
        @SuppressWarnings("unchecked")
        public void processRow(ResultSet rs) throws SQLException {
            Map mp = new HashMap();
            int columnSize = rs.getMetaData().getColumnCount();
            try {
                String content;/*w w  w. j a  va 2 s. c  o m*/
                Object obj;
                String columnName;
                for (int i = 1; i <= columnSize; i++) {
                    columnName = rs.getMetaData().getColumnName(i);
                    content = "";
                    obj = rs.getObject(i);
                    if (obj != null) {
                        content = rs.getObject(i).toString().trim();
                    }

                    mp.put(columnName, content);
                }
                lstValue.add(mp);
            } catch (Exception e) {
                logger.error(e);
            }
        }
    });
    return lstValue;
}

From source file:ru.org.linux.tag.TagDao.java

/**
 *  ??    ./* ww  w.j  av  a 2s. c om*/
 *
 * @param firstLetter       : ?  ? ,    
 * @return ?? 
 */
Map<String, Integer> getTagsByFirstLetter(String firstLetter) {
    final ImmutableMap.Builder<String, Integer> builder = ImmutableMap.builder();
    StringBuilder query = new StringBuilder();
    query.append("select counter, value from tags_values where lower(substr(value,1,1)) = ? ");
    query.append(" and counter > 0 ");
    query.append(" order by value");

    jdbcTemplate.query(query.toString(), new RowCallbackHandler() {
        @Override
        public void processRow(ResultSet resultSet) throws SQLException {
            builder.put(resultSet.getString("value"), resultSet.getInt("counter"));
        }
    }, firstLetter);

    return builder.build();
}

From source file:eionet.meta.dao.mysql.TableDAOImpl.java

/**
 * {@inheritDoc}//from   w w  w. j a v  a  2 s  . co  m
 */
@Override
public List<DataSetTable> searchTables(TableFilter tableFilter) {
    StringBuilder sql = new StringBuilder();

    int nameAttrId = getNameAttributeId();

    Map<String, Object> params = new HashMap<String, Object>();
    params.put("nameAttrId", nameAttrId);
    params.put("parentType", "T");

    sql.append(
            "select dst.TABLE_ID, dst.SHORT_NAME, ds.SHORT_NAME as datasetName, ds.REG_STATUS, dst.IDENTIFIER, ds.IDENTIFIER, ds.DATASET_ID, ");
    sql.append(
            "(select VALUE from ATTRIBUTE where M_ATTRIBUTE_ID = :nameAttrId and DATAELEM_ID = dst.TABLE_ID ");
    sql.append("and PARENT_TYPE = :parentType limit 1 ) as fullName ");
    sql.append("from DS_TABLE as dst ");
    sql.append("inner join DST2TBL as dst2ds on dst2ds.TABLE_ID = dst.TABLE_ID ");
    sql.append("inner join DATASET as ds on dst2ds.DATASET_ID = ds.DATASET_ID ");
    sql.append("where ds.DELETED is null ");
    sql.append("and ds.WORKING_COPY = 'N' ");
    sql.append("");

    if (StringUtils.isNotEmpty(tableFilter.getIdentifier())) {
        sql.append("and dst.IDENTIFIER like :identifier ");
        params.put("identifier", "%" + tableFilter.getIdentifier() + "%");
    }

    if (StringUtils.isNotEmpty(tableFilter.getShortName())) {
        sql.append("and dst.SHORT_NAME like :shortName ");
        params.put("shortName", "%" + tableFilter.getShortName() + "%");
    }

    boolean attributesExist = false;
    for (Attribute attr : tableFilter.getAttributes()) {
        if (StringUtils.isNotEmpty(attr.getValue())) {
            attributesExist = true;
            break;
        }
    }

    if (attributesExist) {
        for (int i = 0; i < tableFilter.getAttributes().size(); i++) {
            Attribute a = tableFilter.getAttributes().get(i);
            String idKey = "attrId" + i;
            String valueKey = "attrValue" + i;
            if (StringUtils.isNotEmpty(a.getValue())) {
                sql.append("and dst.TABLE_ID in ( ");
                sql.append("select a.DATAELEM_ID from ATTRIBUTE a where a.PARENT_TYPE = :parentType ");
                sql.append(" and a.M_ATTRIBUTE_ID = :" + idKey + " and a.VALUE like :" + valueKey);
                sql.append(") ");
                params.put(idKey, a.getId());
                params.put(valueKey, "%" + a.getValue() + "%");
            }

        }
    }

    sql.append("order by ds.IDENTIFIER asc, ds.DATASET_ID desc, dst.IDENTIFIER asc, dst.TABLE_ID desc");

    // LOGGER.debug("SQL: " + sql.toString());

    final List<DataSetTable> resultList = new ArrayList<DataSetTable>();

    getNamedParameterJdbcTemplate().query(sql.toString(), params, new RowCallbackHandler() {

        String curDstID = null;
        String curDstIdf = null;

        @Override
        public void processRow(ResultSet rs) throws SQLException {
            DataSetTable table = new DataSetTable();
            table.setId(rs.getInt("dst.TABLE_ID"));
            table.setShortName(rs.getString("dst.SHORT_NAME"));
            table.setDataSetStatus(rs.getString("ds.REG_STATUS"));
            table.setName(rs.getString("fullName"));
            table.setDataSetName(rs.getString("datasetName"));

            // skip tables that do not actually exist (ie trash from some erroneous situation)
            if (StringUtils.isEmpty(rs.getString("dst.IDENTIFIER"))) {
                return;
            }

            String dstID = rs.getString("ds.DATASET_ID");
            String dstIdf = rs.getString("ds.IDENTIFIER");
            if (dstID == null && dstIdf == null) {
                return;
            }

            // Adding only the most recent version of data set table into the result
            if (curDstIdf == null || !curDstIdf.equals(dstIdf)) {
                curDstIdf = dstIdf;
                curDstID = dstID;
            } else if (!dstID.equals(curDstID)) {
                return;
            }
            resultList.add(table);
        }

    });

    Collections.sort(resultList);
    return resultList;
}

From source file:ru.org.linux.user.UserTagDao.java

/**
 *  ?? ?  ? ?.//from w  w w  .  j a  v  a  2s  . c  o  m
 *
 * @param userId       ?
 * @param isFavorite    (true)   (false)
 * @return ??  ?
 */
public ImmutableList<String> getTags(int userId, boolean isFavorite) {
    MapSqlParameterSource parameters = new MapSqlParameterSource();
    parameters.addValue("user_id", userId);
    parameters.addValue("is_favorite", isFavorite);

    final ImmutableList.Builder<String> tags = ImmutableList.builder();

    jdbcTemplate.query("SELECT tags_values.value FROM user_tags, tags_values WHERE "
            + "user_tags.user_id=:user_id AND tags_values.id=user_tags.tag_id AND user_tags.is_favorite=:is_favorite "
            + "ORDER BY value", parameters, new RowCallbackHandler() {
                @Override
                public void processRow(ResultSet rs) throws SQLException {
                    tags.add(rs.getString("value"));
                }
            });

    return tags.build();
}

From source file:org.string_db.jdbc.Postgres2HSQLDB.java

void dumpTableData(final String schema, final String table, String filter, final StringBuilder result,
        final String[] columnsToInclude) {
    final String selectedColumns = columnsToInclude != null ? Joiner.on(',').join(columnsToInclude) : "*";
    final String sql = "SELECT " + selectedColumns + " FROM " + schema + "." + table
            + (filter != null ? " WHERE " + filter : "");
    final String columns = columnsToInclude != null ? "(" + Joiner.on(", ").join(columnsToInclude) + ")" : null;

    result.append("SET SCHEMA ").append(schema).append(";\n");
    jdbcTemplate.query(sql, new RowCallbackHandler() {
        @Override/* w w  w.ja v a  2s.c om*/
        public void processRow(ResultSet rs) throws SQLException {
            result.append("INSERT INTO ").append(table);
            if (columns != null)
                result.append(columns);
            result.append(" VALUES(");
            for (int i = 0; i < rs.getMetaData().getColumnCount(); i++) {
                if (i > 0) {
                    result.append(", ");
                }
                Object value = rs.getObject(i + 1);
                if (value == null) {
                    result.append("NULL");
                } else {
                    String outputValue = value.toString();
                    // In a string started with ' (singlequote) use '' (two singlequotes) to create a ' (singlequote).
                    //see http://www.hsqldb.org/doc/guide/ch09.html#expression-section
                    //XXX use Connection.escapeString ?
                    outputValue = outputValue.replaceAll("'", "''");
                    result.append("'" + outputValue + "'");
                }
            }
            result.append(");\n");
        }
    });
}

From source file:ru.org.linux.tag.TagDao.java

/**
 *    ,  ???./*from www. j  a v  a2 s  .c om*/
 *
 * @return ?? 
 */
public Map<String, Integer> getAllTags() {
    final ImmutableMap.Builder<String, Integer> builder = ImmutableMap.builder();
    jdbcTemplate.query(QUERY_ALL_TAGS, new RowCallbackHandler() {
        @Override
        public void processRow(ResultSet resultSet) throws SQLException {
            builder.put(resultSet.getString("value"), resultSet.getInt("counter"));
        }
    });
    return builder.build();
}

From source file:com.baidu.rigel.biplatform.tesseract.dataquery.service.impl.SqlDataQueryServiceImpl.java

/**
 * ?SQL??resultRecord list//w  ww . j a v  a2s  .c  o m
 * @param sqlQuery
 * @param dataSource
 * @param limitStart
 * @param limitEnd
 * @return
 */
private SearchIndexResultSet querySqlList(SqlQuery sqlQuery, DataSource dataSource, long limitStart,
        long limitEnd) {
    long current = System.currentTimeMillis();
    if (sqlQuery == null || dataSource == null || limitEnd < 0) {
        throw new IllegalArgumentException();
    }

    sqlQuery.setLimitMap(limitStart, limitEnd);

    this.initJdbcTemplate(dataSource);

    Meta meta = new Meta(sqlQuery.getSelectList().toArray(new String[0]));
    SearchIndexResultSet resultSet = new SearchIndexResultSet(meta, 1000000);

    jdbcTemplate.query(new PreparedStatementCreator() {

        @Override
        public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
            PreparedStatement pstmt = con.prepareStatement(sqlQuery.toSql(), ResultSet.TYPE_FORWARD_ONLY,
                    ResultSet.CONCUR_READ_ONLY);
            if (con.getMetaData().getDriverName().toLowerCase().contains("mysql")) {
                pstmt.setFetchSize(Integer.MIN_VALUE);
            }
            return pstmt;
        }
    }, new RowCallbackHandler() {

        @Override
        public void processRow(ResultSet rs) throws SQLException {
            List<Object> fieldValues = new ArrayList<Object>();
            String groupBy = "";
            for (String select : sqlQuery.getSelectList()) {
                fieldValues.add(rs.getObject(select));
                if (sqlQuery.getGroupBy() != null && sqlQuery.getGroupBy().contains(select)) {
                    groupBy += rs.getString(select) + ",";
                }
            }

            SearchIndexResultRecord record = new SearchIndexResultRecord(
                    fieldValues.toArray(new Serializable[0]), groupBy);
            resultSet.addRecord(record);
        }
    });
    LOGGER.info(String.format(LogInfoConstants.INFO_PATTERN_FUNCTION_END, "querySqlList",
            "[sqlQuery:" + sqlQuery.toSql() + "][dataSource:" + dataSource + "][limitStart:" + limitStart
                    + "][limitEnd:" + limitEnd + "] cost" + (System.currentTimeMillis() - current + "ms!")));
    return resultSet;
}

From source file:com.mvdb.etl.dao.impl.JdbcOrderDAO.java

@Override
public Map<String, ColumnMetadata> findMetadata() {
    String sql = "SELECT * FROM ORDERS limit 1";
    final Map<String, ColumnMetadata> metaDataMap = new HashMap<String, ColumnMetadata>();

    getJdbcTemplate().query(sql, new RowCallbackHandler() {

        @Override/*w  ww  . j a v a 2 s  .c o  m*/
        public void processRow(ResultSet row) throws SQLException {
            ResultSetMetaData rsm = row.getMetaData();
            int columnCount = rsm.getColumnCount();
            for (int column = 1; column < (columnCount + 1); column++) {
                ColumnMetadata metadata = new ColumnMetadata();
                metadata.setColumnLabel(rsm.getColumnLabel(column));
                metadata.setColumnName(rsm.getColumnName(column));
                metadata.setColumnType(rsm.getColumnType(column));
                metadata.setColumnTypeName(rsm.getColumnTypeName(column));

                metaDataMap.put(rsm.getColumnName(column), metadata);
            }

        }
    });

    return metaDataMap;
}

From source file:org.brickhouse.impl.SqlTable.java

@Override
public void readAll(final Filter filter, final Consumer<HMap> consumer, boolean fillDii) {
    final Map<String, String> disCache = fillDii ? new HashMap<>() : null;

    long start = System.nanoTime();
    final MutableInt count = new MutableInt();
    final MutableInt included = new MutableInt();

    try {/*  w w  w.ja  v  a 2 s  .  c o  m*/
        jt.query(select, new RowCallbackHandler() {
            @Override
            public void processRow(ResultSet rs) throws SQLException {
                HMap map = toMap(rs.getString(1));
                count.increment();
                if (filter.include(map, pather)) {
                    fillDii(map, disCache);
                    consumer.accept(map);
                    included.increment();
                }
            }
        });
    } catch (CancelReadException e) {
        // no op
    }

    if (stats)
        saveStats(filter.toString(), count.intValue(), included.intValue(), fillDii, System.nanoTime() - start,
                System.currentTimeMillis());
}

From source file:com.oracle2hsqldb.dialect.Oracle9Dialect.java

/**
 * performance improvement over GenericDialect's getColumns()
 *//*from   w  ww . j  a va  2  s  .c o m*/
public Iterator getColumns(final DataSource dataSource, String schemaName) throws SQLException {
    final List specs = new LinkedList();
    new JdbcTemplate(dataSource).query("SELECT " + "column_name, " + "table_name, " + "data_type, "
            + "NVL(data_precision, data_length) AS column_size," + "data_scale AS decimal_digits,"
            + "DECODE(nullable, 'Y', 1, 0) AS nullable," + "data_default AS column_def "
            + "FROM user_tab_columns", new RowCallbackHandler() {
                public void processRow(ResultSet columns) throws SQLException {
                    // retrieve values ahead of time, otherwise you get a stream
                    // closed error from Oracle
                    String columnName = columns.getString("COLUMN_NAME");
                    if (log.isDebugEnabled())
                        log.debug("Reading column " + columnName);
                    String tableName = columns.getString("TABLE_NAME");
                    try {
                        int dataType = getType(columns.getString("DATA_TYPE"));

                        int columnSize = columns.getInt("COLUMN_SIZE");
                        int decimalDigits = columns.getInt("DECIMAL_DIGITS");
                        boolean isNullable = columns.getBoolean("NULLABLE");
                        String columnDef = columns.getString("COLUMN_DEF");
                        specs.add(new Column.Spec(tableName, new Column(columnName, dataType, columnSize,
                                decimalDigits, isNullable, parseDefaultValue(columnDef, dataType))));
                    } catch (IllegalArgumentException e) {
                        log.error("Problems with column " + columnName + " from table name  " + tableName);
                        throw new SQLException(
                                "Problems with column " + columnName + " from table " + tableName, e);
                    }
                }
            });
    return specs.iterator();
}