Getting List<String> using Spring JdbcTemplate

12,464

To get a List you try something like this.

List<String> data= logJdbcTemplate.queryForList(query,String.class)

The reason why your code with BeanPropertyRowMapper is not working could be probably because (It's a logical guess) When you provide a bean (say User.class) Spring must be initializing the class (probably using reflection) and then mapping all the fields with the column_name in ResultSet provided by the database.

But in case of String.class it is not able to find any field mapping to your ResultSet. But it has already created the object and that's why it is return 4 blank objects.

Share:
12,464
Vicky
Author by

Vicky

A software developer with zeal to learn new things all the time!!

Updated on June 14, 2022

Comments

  • Vicky
    Vicky almost 2 years

    I want to fetch a list of String objects from database using Spring JdbcTemplate:

    This works:

    List<String> myList = this.logJdbcTemplate.query(this.dbQuery, new Object[] {this.someKey}, new RowMapper() {
        public Object mapRow(ResultSet resultSet, int i) throws SQLException {
            return resultSet.getString(1);
        }
    });
    

    with myList containing the Strings returned from database.

    However, the none of the following work:

    List<String> myList = this.logJdbcTemplate.query(this.dbQuery, new Object[] {this.someKey}, new BeanPropertyRowMapper(String.class));
    
    List<String> myList = this.logJdbcTemplate.query(this.dbQuery, new Object[] {this.someKey}, new BeanPropertyRowMapper<String>(String.class));
    
    List<String> myList = (List<String>)this.logJdbcTemplate.query(this.dbQuery, new Object[] {this.someKey}, new BeanPropertyRowMapper<String>(String.class));
    

    Strangely, when I print the size of the rulesList after above statement, the size returned is 4, which are the number of Strings returned from database. However, the list has all blank elements when checking during debug.

    What's the issue ?