hql query to fetch data and sum of amount

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-13 05:04:30

问题


I am writing query to fetch data from tables

my hql query is

SELECT distinct bd FROM BillDetails AS bd
    LEFT JOIN FETCH bd.customerDetails AS cd
    LEFT JOIN FETCH bd.billProductList AS bpd
    LEFT JOIN FETCH bpd.product AS pd
    WHERE bd.billNo=:id
    AND bd.client.id=:cid

Above query is working properly

I want to write query to fetch sum of all amount field of billPaidDetailses.

billPaidDetailses is a list in BillDetails class.

I am trying following query for that but it is not working

String hql = "select distinct bd,sum(bpds.amount) from BillDetails as bd "
                    + "left join fetch bd.customerDetails as cd "
                    + "left join fetch bd.billProductList as bpd "
                    + "left join fetch bpd.product as pd "
                    +"left join fetch bd.billPaidDetailses as bpds "
                    + "where bd.billNo=:id "
                    + "and bd.client.id=:cid ";

The error returned is

org.hibernate.loader.MultipleBagFetchException: cannot simultaneously fetch 
    multiple bags

回答1:


Quoting Hibernate manual:

Hibernate also does not currently expand a grouped entity, so you cannot write group by cat if all properties of cat are non-aggregated. You have to list all non-aggregated properties explicitly.

It means you will have to add all properties for all joined entities:

  • BillDetails bd
  • bd.customerDetails cd
  • bd.billProductList bpd
  • bpd.product pd

giving you a HQL query like:

select distinct bd, sum(bpds.amount) 
from BillDetails as bd "
left join fetch bd.customerDetails as cd
left join fetch bd.billProductList as bpd
left join fetch bpd.product as pd
left join fetch bd.billPaidDetailses as bpds
where 
    bd.billNo=:id and bd.client.id=:cid
group by
    bd.id,
    bd.propertyA,
    bd.propertyB,
    cd.id,
    cd.propertyC,
    cd.propertyD,
    pd.id,
    pd.propertyE,
    pd.propertyF,
    bpds.id,
    bpds.propertyG,
    bpds.propertyH

The only advantage over a native SQL query is that Hibernate manages to regroup entities in a hierarchical structure.



来源:https://stackoverflow.com/questions/24673129/hql-query-to-fetch-data-and-sum-of-amount

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!