Request for sleeping criteria with By and aliasToBean

I have a table / object called SaleRecord with fields like

@Entity public class SaleRecord { private Long id; private String type; private Double amount; //Getter and Setter and more fields } 

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; } } 
+4
source share
1 answer

I think he is not able to transform. as in the column "Criterion" the name is "type", but CollectionDO.java has the field "accountName"

Try this as follows (using this add version to specify an alias name):

 Criteria criteria = getSession() .createCriteria(SaleRecord.class) .add(Restrictions.between("date", reportForm.getFromDate(), reportForm.getToDate())); .setProjection(Projections.projectionList() .add(Projections.property("type"), "accountName") .add(Projections.sum("amount")) .add(Projections.groupProperty("type"))); .setResultTransformer(Transformers.aliasToBean(CollectionDO.class)) return (List<CollectionDO>) criteria.list(); 
+10
source

Source: https://habr.com/ru/post/1435656/


All Articles