我正在研究一种使用NamedParameterJdbcTemplate从MySQL数据库获取一些数据的方法. listCurrentRecords应该从数据库返回Customer,Product和SalesOrder的对象类型列表. objectType是从在方法(1 || 2 || 3)内传递的参数定义的,并且在类中更早地定义为public变量.
public static final int TYPE_PRODUCT = 1;
public static final int TYPE_CUSTOMER = 2;
public static final int TYPE_SALESORDER = 3;
下面提供了该方法.
public static List listCurrentRecords(int objectType)
{
// PRODUCT
if ( objectType == 1 ){
}
//CUSTOMER
else if ( objectType == 2 ){
}
// SALESORDER
else if ( objectType == 3 ){
}
return null;
// return new ArrayList();
}
假设objectType == 2,那么它将需要使用getMyCustomer方法(从Product和SalesOrder同样使用它们将使用各自的方法)从Customer表中获取一些数据,如下所示,
public static List getMyCustomer(){
return jdbc.query("select * from Customer", new RowMapper() {
public Customer mapRow(ResultSet rs, int rowNum) throws SQLException {
Customer customer = new Customer();
customer.setCustomerID(rs.getString("CustomerID"));
customer.setName( rs.getString("Name"));
customer.setAddress( rs.getNString("Address"));
customer.setPhone1(rs.getNString("Phone 1"));
customer.setPhone2(rs.getNString("Phone 2"));
customer.setCreditLimit(rs.getDouble("Credit Limit"));
customer.setCurrentCredit(rs.getDouble("Current Credit"));
return customer;
}
});
在else if(objectType == 2){}内部,我想调用getMyCustomer方法并获取List< Customer>.那里.但是,方法listCurrentRecords的返回类型为List< Object>.如何从List< Customer>转换列出< Object>.我提供了以下伪代码,
// customer
else if ( objectType == 2 ){
List myCustomer = getMyCustomer();
// how to convert ***myCustomer*** to List ?
}
感谢您提供一些有关如何用Java正确编写的帮助.
解决方法:
由于需要对象类型(记住泛型是编译时类型检查功能),因此可以使用addAll或采用第二个List的构造函数.喜欢
List myCustomer = new ArrayList<>(getMyCustomer());
要么
List al = new ArrayList<>();
// ...
al.addAll(getMyCustomer());
标签:generics,jdbc,java,mysql,object
来源: https://codeday.me/bug/20191027/1946580.html