我有一个JdbcTemplate
使用 queryForList
从数据库表中获取所有记录的查询。我有一个在 ArrayList
上运行的类(class)主要是希望将列表转换为 ArrayList<Customer>
。在调试器中,它可以很好地检索记录,但我无法弄清楚如何强制转换 Object
到 Customer
并创建一个 ArrayList
类型 Customer
。这是我的代码:
public static ArrayList<Customer> getCustomers(){
String query = "SELECT customerId,lastName,firstName,email,address,city,state,zip FROM " +
"Customers";
List customerList = jdbcTemplate.queryForList(query);
ArrayList<Customer> customerArrayList = new ArrayList(customerList);
return customerArrayList;
}
最佳答案
有什么原因吗List
是裸体而不是 List<Customer>
?我相信这就是您需要解决的全部问题。
注意ArrayList
支持构造函数
ArrayList(Collection<? extends E> c)
您正在尝试使用哪个。
来自Spring's JDBC Template documentation看来您需要“提示”返回类型:
<T> List<T> queryForList(String sql, Class<T> elementType)
即调用
List<Customer> customerList = jdbcTemplate.queryForList(query, Customer.class);
关于java - 如何正确地将 List 转换为我的对象类型的 ArrayList?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35516208/