次のようなフィールドを持つSaleRecordというテーブル/エンティティがあります
@Entity
public class SaleRecord {
private Long id;
private String type;
private Double amount;
//Getter and Setter and more fields
}
基準を使用してクエリの下に書きたい
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 は、結果を入力したいもう 1 つの 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;
}
}