我正在 Spring Framework 中创建 MVC Web 应用程序,我需要将 Apache DBUtils 结果集中的行转换为由嵌套对象组成的 JavaBeans。
关于我发现的极少数示例,我创建了这个 RowProcessor 实现。
public class MonthOrderCountHandler extends BasicRowProcessor {
@Override
public Object toBean(ResultSet rs, Class type) throws SQLException {
// Year
Year year = new Year();
year.setYearNo(rs.getInt("yearNo"));
year.setYear4(rs.getString("year4"));
year.setYear2(rs.getString("year2"));
// Quarter
Quarter quarter = new Quarter();
quarter.setQuarter(rs.getInt("quarter"));
// Month
Month m = new Month();
m.setYear(year);
m.setQuarter(quarter);
m.setMonthAbbreviation(rs.getString("monthAbbreviation"));
m.setMonthName(rs.getString("monthName"));
m.setMonthNo(rs.getInt("monthNo"));
// Final bean
MonthOrderCount result = new MonthOrderCount();
result.setMonth(m);
result.setOrderCount(rs.getInt("orderCount"));
return result;
}
}
问题:我想知道如何在我的 DAO 对象中使用这个行处理器,以及这个实现是否正确?
通常我以这种方式将行转换为 JavaBean:
ResultSetHandler<List<MonthOrderCount>> listUrlHandler = new BeanListHandler<>(MonthOrderCount.class);
但在我的情况下,首先需要创建嵌套对象,然后创建最终的 JavaBean,所以我假设我需要自定义行处理器。
我的域对象的结构是:
MonthOrderCount 类:
public class MonthOrderCount {
private Month month;
private int orderCount;
}
月班:
public class Month {
private Quarter quarter;
private Year year;
private int monthNo;
private String monthName;
private String monthAbbreviation;
}
四分之一班:
public class Quarter {
private int quarter;
private String abbreviation;
}
年级:
public class Year {
private int yearNo;
private String year2;
private String year4;
}
编辑:我问是因为我的结果看起来像这样。orderCount 变量已正确填充,但月份在所有情况下都为空。对我来说最奇怪的是 - toBean() 方法永远不会被调用。
2013-03-10 17:09:46 INFO ChartDataService:29 - [MonthOrderCount{month=null, orderCount=1863}, MonthOrderCount{month=null, orderCount=2262}, MonthOrderCount{month=null, orderCount=2531}, MonthOrderCount {month=null, orderCount=2379}, MonthOrderCount{month=null, orderCount=2106}, MonthOrderCount{month=null, orderCount=1498}, MonthOrderCount{month=null, orderCount=1300}, MonthOrderCount{month=null, orderCount =1578}, MonthOrderCount{month=null, orderCount=2385}, MonthOrderCount{month=null, orderCount=2991}, MonthOrderCount{month=null, orderCount=2219}, MonthOrderCount{month=null, orderCount=1943}, MonthOrderCount{月=空,订单计数=264}]