使用Hibernate Criteria按日期汇总和分组

时间:2016-11-13 09:30:50

标签: java hibernate jsf primefaces

我有以下示例帐户表:

id  amount  amountDate
1  2.2  2016-09-01
2  4.4  2016-09-02
...  ...  ...
31  1.1  2016-10-01
32  2.2  2016-10-2

我想按amountDate将金额列组合并到结果:

Amount  Amount_Month
6.6  2016-September
3.3  2016-October

(此结果必须显示在primefaces数据表中)

这就是我的尝试:

AccountDAO.java 中,我有以下两个功能:

public Double getTotalAmmount(){
         Session session = sessionFactory.openSession();
         Criteria cr = session.createCriteria(Account.class);
         cr.setProjection(Projections.sum("ammount"));
         List total = cr.list();
         session.close();

       return (Double)total.get(0);
   }

public List getD()
{
    Session session = sessionFactory.openSession();
    Criteria criteria = session.createCriteria(Account.class);
    ProjectionList projectionList = Projections.projectionList(); 
    projectionList.add(Projections.sqlGroupProjection("date(ammountDate) as amD", "amD", new String[] { "amD" }, new Type[] { StandardBasicTypes.DATE }));
    criteria.setProjection(projectionList);
    return criteria.list();
}

AccountBean.java

private Double totalAmmount;
private List<Account> total;

//with their setter and getter

    @PostConstruct
    public void onCreate(){ 
        loadAccounts();    
    }

    public void loadAccounts(){ 
        total = AccountDAO.getInstance().getD();
        totalAmmount = AccountDAO.getInstance().getTotalAmmount();
    }

这是primefaces数据表:

<p:panel id="list" header="Accounts">
                        <h:form id="actores">
                            <p:dataTable 
                                value="#{accountBean.totalAmmount}" 
                                var="account" 
                                id="dataTable"
                                paginator="true" 
                                rows="12">

                                <p:column>
                                    <f:facet name="header">Sum_of_Ammount</f:facet>
                                    <h:outputText value="#{accountBean.totalAmmount}" />
                                </p:column>

                                <p:column>
                                    <f:facet name="header">Months</f:facet>
                                    <h:outputText value="#{accountBean.total}" />
                                </p:column>
                            </p:dataTable>
                        </h:form>
                    </p:panel>

但结果是:

Sum_of_Ammount   Months

59.20000000000002  [[Ljava.lang.Object;@2093e746, 
                       [Ljava.lang.Object;@30890fe4, ...

1 个答案:

答案 0 :(得分:0)

您将列表返回到客户端视图。因此它没有正确显示。

private Double totalAmmount;
private List<Account> total;

//with their setter and getter

@PostConstruct
public void onCreate(){ 
    loadAccounts();    
}

public void loadAccounts(){ 
    total = AccountDAO.getInstance().getD(); // this is List.
    totalAmmount = AccountDAO.getInstance().getTotalAmmount();
}