我有名为 SaleRecord 的表/实体,其中包含以下字段
@Entity
public class SaleRecord {
private Long id;
private String type;
private Double amount;
//Getter and Setter and more fields
}
我想用 Criteria 写下面的查询
SELECT s.type AS accountName, SUM(s.amount) AS amount
FROM salerecord s
GROUP BY s.type
我在 Hibernate 中使用普通 SQL 编写为(它的工作)
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 是另一个 POJO 类,我想在其中填充结果。
但是想使用条件来编写,那么如何编写这个查询并将结果转换为 CollectionDO 类。我试过关注但没有工作
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;
}
}