I have a table / object called SaleRecord with fields like
@Entity public class SaleRecord { private Long id; private String type; private Double amount;
I want to write a query below using criteria
SELECT s.type AS accountName, SUM(s.amount) AS amount FROM salerecord s GROUP BY s.type
I wrote using plain SQL in Hibernate as (its work)
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 I want to write using criteria, So how to write this query and convert the result to a CollectionDO class. I tried but did not work
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; } }
source share