Reputation: 1388
I would like to get ALL rows from my simplejdbctemplate query tables and would like to add them to a list. What would be the best way to do that? I've tried this:
List<String> carbrands = (List<String>) jdbcTemplate.queryForList("select brand from cars", String.class);
So I'd expect a list of strings like:
toyota
hyundai
bmw
benz
...
But I can't get this to work. And if I try to do this for multiple types, I get stuck:
List<Car> values = (List<Car>) jdbcTemplate.queryForList("select name,brand,value from cars", Car.class);
This doesn't work either. I'd like it to return Cars, which I defined as name, brand, value. But... I've googled around and can't find a solution. Any suggestions?
Upvotes: 2
Views: 4992
Reputation: 136002
1) query 1 is correct and should work.
2) query 2 should be
List<Car> list = jdbcTemplate.query("select name,brand,value from cars", new BeanPropertyRowMapper<Car>(Car.class));
Car should be a valid JavaBean - must have a public no-arg constructor and public setters / getters
public class Car {
String name;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
...
}
alternatevely you can read cars as maps of columns
List<Map<String, Object>> cars = jdbcTemplate.queryForList("select * from cars");
for(Map car : cars) {
String brand = (String)car.get("brand");
String name = (String)car.getName("name");
....
}
Upvotes: 3