简体   繁体   中英

JPA 2 Criteria - group by and count

I have two entities, ShoppingCart and ShoppingCartLine. ShoppingCart has a collection of 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.

Here is the mapping in the ShoppingCart class:

@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:

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.

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

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" ) ));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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