简体   繁体   English

JPA 2标准-按和分组

[英]JPA 2 Criteria - group by and count

I have two entities, ShoppingCart and ShoppingCartLine. 我有两个实体,ShoppingCart和ShoppingCartLine。 ShoppingCart has a collection of ShoppingCartLines. ShoppingCart有ShoppingCartLines的集合。 I am trying to create a JPA query using criteria to get a list of ShoppingCart ids and the number of ShoppingCartLines each ShoppingCart has. 我正在尝试使用条件创建JPA查询,以获取ShoppingCart ID的列表以及每个ShoppingCart具有的ShoppingCartLines的数量。

Here is the mapping in the ShoppingCart class: 这是ShoppingCart类中的映射:

@OneToMany(mappedBy = "shoppingCart", fetch = FetchType.EAGER, cascade = CascadeType.ALL, orphanRemoval=true)
private Set<ShoppingCartLine> shoppingCartLines = new TreeSet<ShoppingCartLine>();

Here is the code I am attempting to create my JPA query with: 这是我尝试使用以下代码创建JPA查询的代码:

CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Tuple> cq = cb.createTupleQuery();
Root<ShoppingCart> carts = cq.from( ShoppingCart.class );
Join<ShoppingCart, ShoppingCartLine> lines = carts.join( "shoppingCartLines", JoinType.LEFT);
cq.multiselect( carts.<Long>get( "id" ), cb.count( lines ));
cq.groupBy( carts.<Long>get("id") );

Query tq = em.createQuery( cq );
return tq.getResultList();

When I run this I get an SQLGrammerException, the SQL produced does not look correct to me. 运行此命令时,我得到一个SQLGrammerException,对我来说生成的SQL看起来不正确。

select
    shoppingca0_.id as col_0_0_,
    count(.) as col_1_0_ 
from
    SHOPPINGCART shoppingca0_ 
left outer join
    SHOPPINGCARTLINE shoppingca1_ 
        on shoppingca0_.id=shoppingca1_.shoppingCart_id,
    SHOPPINGCARTLINE shoppingca2_ 
where
    shoppingca0_.id=shoppingca2_.shoppingCart_id 
group by
    shoppingca0_.id

I should mention I am using Hibernate 3.5.4 with MySQL5Dialect 我应该提到我正在将Hibernate 3.5.4与MySQL5Dialect一起使用

This is the query I am wanting to generate: 这是我要生成的查询:

select
    sc.id,
    count(scl.id)
from
    shoppingcart sc
left join
    shoppingcartline scl
on
    scl.shoppingCart_id = sc.id
group by
    sc.id

Any idea what I'm doing wrong? 知道我在做什么错吗? Thanks. 谢谢。

Try to replace join and multiselect lines with 尝试将连接和多选行替换为

SetJoin<ShoppingCart, ShoppingCartLine> lines = 
    carts.joinSet( "shoppingCartLines", JoinType.LEFT);
cq.multiselect( carts.<Long>get( "id" ), cb.count( lines.<Long>get( "id" ) ));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM