简体   繁体   中英

Hibernate criteria + calculation in Projection List

Invoice

id description rate amount
1 Invoice A 3.0 10.0
2 Invoice B 4.0 20.0
3 Invoice 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

Using projection list, is it possible to calculate (amount * rate) and return the sum for all records?

Update 1:

   double dblAmount = 0.0;
   for(Invoice invoice : list){
     dblAmount = dblAmount + (invoice.getRate() * invoice.getAmount());
   }

Using Hibernate 4, I heard that without specifying joins, using this way (invoice.getSomething()) has performance impact?

You can create a @Formula derived property and then create a projection on that:

Derived property:

@Entity
@Table(name="INVOICE")
public class Invoice {
    private double rate;
    private double amount;
    @Formula("rate * amount")
    private double computed;
    // ...
}

Projection:

Projections.sum("computed")
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;

try this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM