我有两个实体,ShoppingCart和ShoppingCartLine。 ShoppingCart有一系列ShoppingCartLines。我正在尝试使用条件创建JPA查询,以获取ShoppingCart ID的列表以及每个ShoppingCart拥有的ShoppingCartLines的数量。
以下是ShoppingCart类中的映射:
@OneToMany(mappedBy = "shoppingCart", fetch = FetchType.EAGER, cascade = CascadeType.ALL, orphanRemoval=true)
private Set<ShoppingCartLine> shoppingCartLines = new TreeSet<ShoppingCartLine>();
以下是我尝试使用以下代码创建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();
当我运行这个时,我得到一个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
我应该提到我正在使用带有MySQL5Dialect的Hibernate 3.5.4
这是我想要生成的查询:
select
sc.id,
count(scl.id)
from
shoppingcart sc
left join
shoppingcartline scl
on
scl.shoppingCart_id = sc.id
group by
sc.id
知道我做错了什么吗?感谢。
答案 0 :(得分:0)
尝试用
替换连接和多选线SetJoin<ShoppingCart, ShoppingCartLine> lines =
carts.joinSet( "shoppingCartLines", JoinType.LEFT);
cq.multiselect( carts.<Long>get( "id" ), cb.count( lines.<Long>get( "id" ) ));