2

我有一个与颜色表有关系的产品表

一个产品可以有多种颜色... exp: 产品A:有红色、绿色、蓝色、黄色。

我希望找到至少包含红色和绿色的产品。

     DetachedCriteria colorCrit = DetachedCriteria.forClass(Color.class);

        ProjectionList colorList = new Projections.projectionList();
        colorList.add(Projections.groupProperty("productID"));
        colorList.add(Projections.rowCount(),"abc");
        colorCrit.setProjection(colorList);

        colorCrit.add(Restrictions.eq("color", "GREEN")
    colorCrit.add(Restrictions.eq("color", "RED")
    colorCrit.add(Restrictions.eq("abc",2);

    Criteria productCrit = new Criteria(Product.class);

    productCrit.add(Suqueries.in("id",colorCrit));
list<Product> productList = productCrit.list();

我使用上面的代码,但我无法通过 on 来实现该组Projections.rowCount()

我试过 .as 但它会导致一个额外的列,使分离的标准不适合 Suqueries。(太多值oracle异常)

colorCrit.add(Restrictions.eq(Projections.rowCount(),2);> 不起作用,因为 rowcount 不是属性 = x

select * from product pd where pd.id = (select cr.productID from color cr where cr.color="RED" or cr.color="GREEN" group by  cr.productID having rowcount=2

以上应该是正确的 SQL 查询。

我可以知道有解决方案吗?

4

1 回答 1

2

我会使用以下查询:

select p from Product p where 
2 = (select count(color.id) from Product p2 
     inner join p2.colors color
     where p2.id = p.id
     and color.color in ('GREEN', 'RED'))

以上可以翻译成标准

Criteria c = session.createCriteria(Product.class, "p")

DetachedCriteria sub = DetachedCriteria.forClass(Product.class, "p2");
sub.createAlias("p2.colors", "color");
sub.add(Restrictions.eqProperty("p2.id", "p.id"))
sub.add(Restrictions.in("color.color", new String[] {"RED", "GREEN"}));
sub.setProjection(Projections.count("color.id"));

c.add(Subqueries.eq(2, sub)); // or 2L

The above assumes that you can't have a product which has 2 colors being RED, i.e. that the tuple (color, product_id) has a unique constraint in the table color.

于 2012-07-11T07:18:25.487 回答