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.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/*from w w w.  jav  a 2 s  .  c om*/
            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:ru.org.linux.section.SectionDaoImpl.java

@Override
public List<Section> getAllSections() {
    final List<Section> sectionList = new ArrayList<>();
    jdbcTemplate.query(/*  w  w  w .  j  a v a 2 s . co m*/
            "SELECT id, name, imagepost, imageallowed, vote, moderate, scroll_mode, restrict_topics FROM sections ORDER BY id",
            new RowCallbackHandler() {
                @Override
                public void processRow(ResultSet rs) throws SQLException {
                    Section section = new Section(rs);
                    sectionList.add(section);
                }
            });
    return sectionList;
}

From source file:com.simplymeasured.prognosticator.ThreadedQueryRunnable.java

@Override
public void run() {
    NamedParameterJdbcTemplate template = new NamedParameterJdbcTemplate(dataSource);

    try {//  www  .  j  a va2s  .  com
        template.query(query, parameters, new RowCallbackHandler() {
            @Override
            public void processRow(ResultSet resultSet) throws SQLException {
                try {
                    Map<String, Object> result = Maps.newHashMap();

                    final ResultSetMetaData metadata = resultSet.getMetaData();

                    for (int i = 1; i <= metadata.getColumnCount(); i++) {
                        String columnTypeName = metadata.getColumnTypeName(i);

                        final Object value;

                        if ("array".equalsIgnoreCase(columnTypeName)) {
                            String stringValue = resultSet.getString(i);

                            if (stringValue != null) {
                                value = objectMapper.readValue(stringValue, List.class);
                            } else {
                                value = null;
                            }
                        } else if ("map".equalsIgnoreCase(columnTypeName)
                                || "struct".equalsIgnoreCase(columnTypeName)) {
                            String stringValue = resultSet.getString(i);

                            if (stringValue != null) {
                                value = objectMapper.readValue(stringValue, Map.class);
                            } else {
                                value = null;
                            }
                        } else {
                            value = resultSet.getObject(i);
                        }

                        result.put(metadata.getColumnName(i), value);
                    }

                    resultQueue.put(result);
                } catch (SQLException se) {
                    LOG.warn("Database error!", se);
                    throw new RuntimeException("Database error!", se);
                } catch (InterruptedException ie) {
                    LOG.warn("Query killed!", ie);
                    throw new RuntimeException("Query killed!", ie);
                } catch (Exception ex) {
                    LOG.warn("Unable to parse row!", ex);
                    throw new RuntimeException("Unable to parse row!", ex);
                }
            }
        });

        resultQueue.put(Collections.<String, Object>emptyMap());
    } catch (DataAccessException dae) {
        try {
            resultQueue.put(Collections.<String, Object>emptyMap());
        } catch (InterruptedException ie) {
            LOG.warn("Queue is dead!", ie);
        }

        LOG.warn("Unable to execute query - attempting to clean up", dae);
    } catch (InterruptedException ie) {
        LOG.warn("Queue is dead!", ie);
    }
}

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

@SuppressWarnings({ "rawtypes", "unchecked" })
public Map query(String sql) {
    final Map map = new HashMap();
    List lstValue = new ArrayList();
    map.put(KEY_VALUES, lstValue);//from   w  ww  .j  av a2 s. c  o  m
    logger.debug(sql);
    getJdbcTemplate().query(sql, new RowCallbackHandler() {
        public void processRow(ResultSet rs) throws SQLException {
            map.put(KEY_META, rs.getMetaData());
            int columnSize = rs.getMetaData().getColumnCount();
            List lstField = new ArrayList();
            try {
                String content;
                ;
                Object obj;
                for (int i = 1; i <= columnSize; i++) {
                    content = "";
                    obj = rs.getObject(i);
                    if (obj != null) {
                        content = rs.getObject(i).toString().trim();
                    }

                    lstField.add(content);
                }
                ((List) map.get(KEY_VALUES)).add(lstField);
            } catch (Exception e) {
                logger.error(e);
            }
        }
    });
    return map;
}

From source file:ru.org.linux.edithistory.EditHistoryDao.java

/**
 *     /?.//from   w w  w . ja v  a 2  s.c  o  m
 *
 * @param id id 
 * @param objectTypeEnum :   
 * @return ??  
 */
public List<EditHistoryDto> getEditInfo(int id, EditHistoryObjectTypeEnum objectTypeEnum) {
    final List<EditHistoryDto> editInfoDTOs = new ArrayList<>();
    jdbcTemplate.query(queryEditInfo, new RowCallbackHandler() {
        @Override
        public void processRow(ResultSet resultSet) throws SQLException {
            EditHistoryDto editHistoryDto = new EditHistoryDto();
            editHistoryDto.setId(resultSet.getInt("id"));
            editHistoryDto.setMsgid(resultSet.getInt("msgid"));
            editHistoryDto.setEditor(resultSet.getInt("editor"));
            editHistoryDto.setOldmessage(resultSet.getString("oldmessage"));
            editHistoryDto.setEditdate(resultSet.getTimestamp("editdate"));
            editHistoryDto.setOldtitle(resultSet.getString("oldtitle"));
            editHistoryDto.setOldtags(resultSet.getString("oldtags"));
            editHistoryDto.setObjectType(resultSet.getString("object_type"));

            editHistoryDto.setOldimage(resultSet.getInt("oldimage"));
            if (resultSet.wasNull()) {
                editHistoryDto.setOldimage(null);
            }

            editHistoryDto.setOldminor(resultSet.getBoolean("oldminor"));
            if (resultSet.wasNull()) {
                editHistoryDto.setOldminor(null);
            }

            editInfoDTOs.add(editHistoryDto);
        }
    }, id, objectTypeEnum.toString());
    return editInfoDTOs;
}

From source file:com.talkingdata.orm.tool.SqlParser.java

public List<ClassDefinition> getTables(final JdbcTemplate jdbcTemplate, String db, final String packageName) {
    final List<ClassDefinition> list = new ArrayList<>();
    String sqlTable = String.format(SQL_TABLE, db);
    jdbcTemplate.query(sqlTable, new RowCallbackHandler() {
        @Override//from   w  ww  .  j  a  v  a2s . c  om
        public void processRow(ResultSet rs) throws SQLException {
            String table = rs.getString("tableName");
            final List<ClassDefinitionColumn> columns = new ArrayList<ClassDefinitionColumn>();
            ClassDefinition classDefinition = new ClassDefinition(packageName, table);
            list.add(classDefinition);
            classDefinition.setColumns(columns);

            String sqlColumn = String.format(SQL_COLUMN, db, table);
            jdbcTemplate.query(sqlColumn, new RowCallbackHandler() {
                @Override
                public void processRow(ResultSet rs) throws SQLException {
                    String columnName = rs.getString("Field");
                    String columnType = rs.getString("Type").replaceAll("\\(\\d+\\)", "").toUpperCase();
                    System.out.println(columnType);
                    String primaryKey = rs.getString("Key");
                    columns.add(new ClassDefinitionColumn(columnName, DATA_MAP.get(columnType), primaryKey));
                }
            });
        }
    });

    return list;
}

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

/**
 * Query database for two columns and collect results in a map.
 * <p/>//from w  w w  .java2 s .  c om
 * <em>Warning</em>: possible SQL injection
 *
 * @param firstColumn  name (escaped if SQL keyword)
 * @param secondColumn name (escaped if SQL keyword)
 * @param table        name
 * @param rowMapper    items collector
 * @param <K>          first column type
 * @param <V>          second column type
 * @param <R>          type for aggregated values from the second column
 * @return
 * @throws org.springframework.dao.DataAccessException if there is any problem executing the query
 */
public <K, V, R> Map<K, R> selectTwoColumns(String firstColumn, String secondColumn, String table,
        final TwoColumnRowMapper<K, V, R> rowMapper) {
    final String query = String.format("SELECT %s, %s FROM %s ", firstColumn, secondColumn, table);
    final Map<K, R> r = new HashMap<>();
    jdbcTemplate.query(query, new RowCallbackHandler() {
        @Override
        public void processRow(ResultSet resultSet) throws SQLException {
            rowMapper.addToMap((K) resultSet.getObject(1), (V) resultSet.getObject(2), r);
        }
    });
    return r;
}

From source file:ru.org.linux.topic.TopicTagDao.java

/**
 *  ??   ./*from w w  w . jav a 2s .c  om*/
 *
 * @param msgid   
 * @return ??  
 */
@Nonnull
public ImmutableList<String> getTags(int msgid) {
    final ImmutableList.Builder<String> tags = ImmutableList.builder();

    jdbcTemplate.query(
            "SELECT tags_values.value FROM tags, tags_values WHERE tags.msgid=? AND tags_values.id=tags.tagid ORDER BY value",
            new RowCallbackHandler() {
                @Override
                public void processRow(ResultSet rs) throws SQLException {
                    tags.add(rs.getString("value"));
                }
            }, msgid);

    return tags.build();
}

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

/**
 *  ?? /*from w w  w . j  a v a2  s.co m*/
 * @param user   
 * @return ?? 
 */
@Nonnull
public Set<Integer> get(@Nonnull User user) {
    final Builder<Integer> builder = ImmutableSet.builder();
    jdbcTemplate.query(queryIgnoreList, new RowCallbackHandler() {
        @Override
        public void processRow(ResultSet resultSet) throws SQLException {
            builder.add(resultSet.getInt("ignored"));
        }
    }, user.getId());
    return builder.build();
}

From source file:de.whs.poodle.WorksheetAutoUnlockScheduler.java

@Scheduled(fixedRate = RATE_MS)
public void unlockWorksheets() {
    log.info("checking for worksheets to unlock...");

    /* query all locked worksheets that have unlock_at in the past, i.e.
     * all worksheets that need to be unlocked right now. */
    jdbc.query(// ww w.j a  v  a  2  s  . c om
            "SELECT id,unlock_at FROM worksheet " + "WHERE NOT unlocked " + "AND unlock_at IS NOT NULL "
                    + "AND unlock_at <= NOW()",

            new RowCallbackHandler() {

                @Override
                public void processRow(ResultSet rs) throws SQLException {
                    int id = rs.getInt("id");
                    Date unlockAt = rs.getTimestamp("unlock_at");

                    log.info("unlocking worksheet {} with unlock_at = {}", id, unlockAt);

                    try {
                        worksheetUnlockEmailService.unlockWorksheetAndSendEmail(id);
                    } catch (MessagingException e) {
                        log.error("failed to send email", e);
                    }
                }
            });
}