Hibernate - 不能一起使用GROUP BY和ORDER BY

时间:2011-04-07 19:37:48

标签: java hibernate hql


这个很奇怪...... 如果包含 ORDER BY ,我有一个忽略GOUP BY的hql查询 它将在没有组的情况下执行查询
但如果我通过删除订单,它将正常工作

  list = getSession().createQuery(
        "SELECT 
  Brand.name as Brand_name 
, Brand.url as Brand_url 
, Brand.email as Brand_email 
, Brand.brandId as Brand_brandId 
, Brand.description as Brand_description 
FROM com.affiliates.hibernate.Brand Brand  
INNER JOIN Brand.users as users 
WHERE 1=1  
AND users.userId>'0' 
order by  Brand.email ASC 
group by brandId"//this one will be ignored because of the order by
    ).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).list();

生成的SQL:

select
        brand0_.NAME as col_0_0_,
        brand0_.URL as col_1_0_,
        brand0_.EMAIL as col_2_0_,
        brand0_.DESCRIPTION as col_3_0_ 
    from
        BRAND brand0_ 
    inner join
        USERS_BRANDS users1_ 
            on brand0_.BRAND_ID=users1_.BRAND_ID 
    inner join
        USER user2_ 
            on users1_.USER_ID=user2_.USER_ID 
    where
        1=1 
        and user2_.USER_ID>'0' 
    order by
        brand0_.EMAIL ASC limit ?       

2 个答案:

答案 0 :(得分:1)

首先,请注意BRAND.BRAND_ID已从SQL中的列投影中删除。这也可能与该组有关也被删除。

其次,请注意查询中没有定义聚合函数。组仅适用于聚合。尝试向所有列添加聚合函数,例如max。这可能是问题的原因

最后,尝试在HQL中完全限定brandId以消除任何混淆:

group by Brand.brandId

答案 1 :(得分:0)

您应该在groupby之后应用orderby但是您已写为

group by brandId"//this one will be ignored because of the order by
    ).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).list();
    order by  Brand.email ASC 

但改为:

for (x1 =0;x1<=nmax[1];x1++){
    a = a + x1 * (x1>upper[1]);
}

然后它会起作用