Getting List<String> using Spring JdbcTemplate
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.
Vicky
A software developer with zeal to learn new things all the time!!
Updated on June 14, 2022Comments
-
Vicky almost 2 years
I want to fetch a list of
String
objects from database using SpringJdbcTemplate
: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 theStrings
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, thesize
returned is 4, which are the number ofStrings
returned from database. However, the list has all blank elements when checking during debug.What's the issue ?