ID 描述 率 量
1 发票A 3.0 10.0
2 发票B 4.0 20.0
3 发票C 5.0 30.0
DetachedCriteria criteria= DetachedCriteria.forClass(Invoice.class)
ProjectionList projList = new ProjectionList();
projList.add(...);
criteria.setProjection(projList);
List list = myDAO.findByCriteria(criteria);
//260
使用投影列表,是否可以计算(金额*费率)并返回所有记录的总和?
更新1:
double dblAmount = 0.0;
for(Invoice invoice : list){
dblAmount = dblAmount + (invoice.getRate() * invoice.getAmount());
}
使用Hibernate 4,我听说没有指定连接,使用这种方式(invoice.getSomething())会对性能产生影响吗?
答案 0 :(得分:1)
您可以创建@Formula
派生属性,然后在其上创建投影:
衍生财产:
@Entity
@Table(name="INVOICE")
public class Invoice {
private double rate;
private double amount;
@Formula("rate * amount")
private double computed;
// ...
}
投影:
Projections.sum("computed")
答案 1 :(得分:0)
double sum=0;
ProjectionList projList = new ProjectionList();
projList.add(Projections.property("rate"));
projList.add(Projections.property("amount"));
criteria.setProjection(projList);
List list=criteria.list();
for (Iterator it = list.iterator(); it.hasNext();) {
double d=1;
Object[] row = (Object[]) it.next();
for (int i = 0; i < row.length; i++) {
d=d*Double.parseDouble(row[i].toString());
}
sum=sum+d;
}
return sum;
试试这个。