6

我有名为 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;
    }     
}
4

1 回答 1

12

我认为它无法转换。如 Criteria 列名称为“type”,但 CollectionDO.java 的字段为“accountName”

尝试如下(使用这个版本的add来指定别名):

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();
于 2012-09-22T12:13:44.920 回答