循环遍历数据库中从起始对象到结束对象的对象

时间:2012-03-13 19:02:58

标签: java

我有一个名为week的表,其中列weekidweeknumberweekyear。 考虑到一个开始的一周,我希望接下来的9周(总共10周)或接下来几周到本周。

我有这个:

Week weekFirst = weekDao.getWeekByID(20);           
Week weekLast = weekDao.getWeekByID(30);
List<Week> weekList= new ArrayList<Week>();

for(int i=weekFirst.getWeekid(); i<=weekLast.getWeekid();i++){
     weekList.add(weekDao.getWeekByID(i));
     if(weeksDAO.getWeekByID(i).getWeeknumber() == now.get(Calendar.WEEK_OF_YEAR)){
          break;            
}

但这不会做,因为它只得到weekId而不是Week Itself(The Object)

我需要获取Object Week本身并将其放入列表中,以便它不会在下一周添加WeekId,但它会根据下一周对象添加。

3 个答案:

答案 0 :(得分:2)

如果我理解你的问题,你基本上是说你的weekDAO对象没有返回Week对象,而是返回来自数据库的Week对象的关联ID。

你的第一段代码:

Week weekFirst - weekDao.getWeekByID(20);

建议“weekDao”实际上是返回一个Week对象(否则它将无法编译)。

因此,如果您正在获取Week对象,则您的weekList.add调用应该添加Week对象。

答案 1 :(得分:0)

WeekDao#getWeekByID应返回Week对象

在DAO中使用此签名

public Week getWeekByID(int);

答案 2 :(得分:0)

根据您的上一条评论,您可以向DAO添加方法:

public List<Week> findAllGreaterThanWeekAndYear(int week, int year) {
    //order by year, week
}

或者,如果你真的知道id,你可以添加DAO方法:

public List<Week> findAllBetween(int idFrom, int idTo) {
    Week from = get(idFrom);
    Week to = get(idTo);
    //select w Week w
    //where w.yearAndWeek between (from.yearAndWeek,to.yearAndWeek)
    //order by w.yearAndWeek
}

然后您的代码变为:

List<Week> weekList= new ArrayList<Week>();
List<Week> weeks = dao.findAllGreaterThanWeekAndYear(...)
List<Week> weeks = dao.findAllBetween(...)

for(Week week : weeks){
 weekList.add(week);
 //TODO: add static getCurrentWeek and override equals
 if(week.equals(Week.getCurrentWeek())){
      break;            
}

根据您的使用方式,您可以添加专门的DAO方法来在查询中进行过滤。