I have table /entity called SaleRecord with fields such as
@Entity
public class SaleRecord {
private Long id;
private String type;
private Double amount;
//Getter and Setter and more fields
}
I want to write below query using Criteria
SELECT s.type AS accountName, SUM(s.amount) AS amount
FROM salerecord s
GROUP BY s.type
I have written using plain SQL in Hibernate as (Its working)
String sql = " SELECT s.type AS accountName, SUM(s.amount) AS amount ";
sql += " FROM salerecord s ";
sql += " GROUP BY s.type ";
List<CollectionDO> incomeList = (List<CollectionDO>) getSession().createSQLQuery(sql).setResultTransformer(Transformers.aliasToBean(CollectionDO.class)).list();
CollectionDO is another POJO class in which I want to populate the result.
But want to write using criteria, So how to write this query and transform result into CollectionDO class.
I have tried following but not working
Criteria criteria = getSession().createCriteria(SaleRecord.class).setResultTransformer(Transformers.aliasToBean(CollectionDO.class));
criteria.setProjection(Projections.property("type"));
criteria.setProjection(Projections.sum("amount"));
criteria.setProjection(Projections.groupProperty("type"));
return (List<CollectionDO>) criteria.list();
CollectionDO.java
public class CollectionDO {
private Double amount;
private String accountName;
public String getAccountName() {
return accountName;
}
public void setAccountName(String accountName) {
this.accountName = accountName;
}
public Double getAmount() {
return amount;
}
public void setAmount(Double amount) {
this.amount = amount;
}
}
Try it as follows (using this version of add to specify the alias name):