Results 1 to 4 of 4

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

  1. #1
    Join Date
    Sep 2009
    Posts
    126

    Default 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. #2
    Join Date
    Jun 2006
    Location
    The Netherlands
    Posts
    13,632

    Default

    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);
    Marten Deinum
    Java Consultant / Pragmatist / Open Source Enthousiast / Author


    Pro Spring MVC: With Web Flow
    Conspect

    Have you read the reference guide.
    Use the [ code ] tags, young padawan

  3. #3
    Join Date
    Sep 2009
    Posts
    126

    Default

    Just what I wanted, thank you!

    PUK

  4. #4
    Join Date
    Jul 2012
    Posts
    1

    Default

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

    namedParameterJdbcTemplate.queryForList(sql, paramMap, elementType)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •