如何用hibernate中的聚合函数编写查询?

时间:2015-02-12 21:02:36

标签: java mysql hibernate function formula

我在MySQL中有一个查询:

select t1.name, t3.name, sum(t2.amount), t3.price,
       t1.price * sum(t2.amount) as 'summ'
from store_catalog t1
    inner join
commission t2 ON (t1.id = t2.idGoodsStore)
    inner join
company_catalog t3 ON (t3.id = t2.idGoodsCompany)
group by t1.id

我读到了@Formula注释,当我使用这个注释时,项目不是部署。我可以用hql编写上面的查询吗?如果不是,我怎么能使用@Formula,我以前的代码:

实体store_catalog的一部分

//aggregate functions
@Formula(" (select sum(amount) from store_catalog) ")
private int summ;

public int getSumm() {
    return summ;
}

public void setSumm(int summ) {
    this.summ = summ;
}

感谢。

1 个答案:

答案 0 :(得分:0)

解决了,我只使用原生SQL,addScalar方法和List of Object [],以及大的查询:

Session session = null;
    List<Object[]> catalogStores = new ArrayList();
    try {
        session = this.sessionFactory.openSession();
        catalogStores = session.createSQLQuery("select \n" +
                "    t1.name as goodsName,\n" +
                "    t3.name as companyName,\n" +
                "    sum(t2.amount) as amountSum,\n" +
                "    t3.price as priceOneGoods,\n" +
                "    (t1.price * sum(t2.amount)) as summ \n" +
                "from\n" +
                "    store_catalog t1\n" +
                "        inner join\n" +
                "    commission t2 ON (t1.id = t2.idGoodsStore)\n" +
                "        inner join\n" +
                "    company_catalog t3 ON (t3.id = t2.idGoodsCompany)\n " +
                "       inner join\n" +
                "   store t4 ON (t1.idStore = " + idStore + ")\n " +
                "group by t1.id")
                .addScalar("goodsName", new StringType())
                .addScalar("companyName", new StringType())
                .addScalar("amountSum", new IntegerType())
                .addScalar("priceOneGoods", new DoubleType())
                .addScalar("summ", new DoubleType())
                .list();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (session != null && session.isOpen())
            session.close();
    }
    return catalogStores;

在我的JSP节目中,如:

<c:forEach items="${statList1}" var="stat">
  <tr class="editField">
    <td>
      <c:out value="${stat[0]}" />
    </td>
    <td>
      <c:out value="${stat[1]}" />
    </td>
    <td>
      <c:out value="${stat[2]}" />
    </td>
    <td>
      <c:out value="${stat[3]}" />
    </td>
    <td>
      <c:out value="${stat[4]}" />
    </td>
  </tr>
</c:forEach>

控制器中的部件代码:

modelAndView.addObject("statList1", myService.myMethod());