日期:2014-05-20  浏览次数:20756 次

哪个高手把这个代码逻辑简化下 谢谢
Java code
 if(!beginTime.equals("")&&!endTime.equals("")) {
                  hql="select sum(d.money)  from Income d where d.company.id="+companyId+" and d.incomeTime>='"+beginTime+"' and d.incomeTime<='"+endTime+"' and d.isDeleted=0";
                  }
                  else if(!beginTime.equals("")) {
                      hql="select sum(d.money)  from Income d where d.company.id="+companyId+" and d.incomeTime>='"+beginTime+"' and d.isDeleted=0";
                  } 
                  else if(!endTime.equals(""))  {
                      hql="select sum(d.money)  from Income d where d.company.id="+companyId+" and d.incomeTime<='"+endTime+"' and d.isDeleted=0";
                  }
                  else {
                      hql="select sum(d.money)  from Income d where d.company.id="+companyId+" and d.isDeleted=0";
                  }


------解决方案--------------------
Java code
StringBuilder buff = new StringBuilder("select sum(d.money) from Income d where d.isDeleted=0 and d.company.id=");
buff.append(companyId);
if (beginTime != null && beginTime.length() != 0) {
    buff.append(" and d.incomeTime >= '").append(beginTime).append("'");
}
if (endTime != null && endTime.length() != 0) {
    buff.append(" and d.incomeTime <= '").append(endTime).append("'");
}
hql = buff.toString();