Announcement Announcement Module
Collapse
No announcement yet.
SimpleJdbcTemplate - elegant way to get a List<String> from single column query? Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • SimpleJdbcTemplate - elegant way to get a List<String> from single column query?

    Hello,

    Let's say I'm selecting a single column from many rows within a table using the SimpleJdbcTemplate. Is there an elegant way to get this as a List<String>? Usually I'd use a RowMapper but when it's just a string I wonder if there's a more elegant solution?

    Code:
        public List<String> doSomething(long val) {
            return jdbc.query("SELECT CODE FROM MY_TABLE WHERE val >= ?",
                    new ParameterizedRowMapper<String>() {
    
                        public String mapRow(ResultSet rs, int arg1) throws SQLException {
                            return rs.getString(1);
                        }
                    },
                    val);
        }

  • #2
    Use JdbcTemplate instead and use that queryForList method. There is one that takes a Class as the argument which is the type to convert to.

    Code:
    List<String> strings = (List<String>) jdbcTemplate.queryForList(query, String.class);

    Comment


    • #3
      Just what I wanted, thank you!

      PUK

      Comment


      • #4
        I do not see any method like queryForList(query, String.class). There is however a method like

        namedParameterJdbcTemplate.queryForList(sql, paramMap, elementType)

        Comment

        Working...
        X